Visual C++ .NET/Class/attribute
Содержание
Creating Custom attribute
#include "stdafx.h"
using namespace System;
[AttributeUsageAttribute(AttributeTargets::Assembly | AttributeTargets::Class)]
public ref class OwnerAttribute : Attribute
{
public:
property String^ DevOwner;
property String^ TestOwner;
OwnerAttribute() { }
};
[ Owner(DevOwner="John") ]
ref class C2
{
};
int main()
{
Attribute^ attribute = Attribute::GetCustomAttribute( C2::typeid,OwnerAttribute::typeid);
if (attribute != nullptr)
{
Console::WriteLine("{0}", attribute);
}
}
Custom attribute
#include "stdafx.h"
using namespace System;
[AttributeUsageAttribute(AttributeTargets::All)]
public ref class OwnerAttribute : Attribute{
public:
property String^ DevOwner;
property DateTime^ CreationDate;
OwnerAttribute(){ }
OwnerAttribute(String^ _DevOwner)
{
DevOwner = _DevOwner;
}
};
[ Owner("Smith")]
ref class C1
{
};
[ Owner(DevOwner="Smith") ]
ref class C2
{
};
Obsolete attribute
#include "stdafx.h"
using namespace System;
ref class C
{
public:
void Method2() {}
[Obsolete("This method is obsolete; use Method2 instead.")]
void Method1() {}
};
int main()
{
C^ c = gcnew C();
c->Method1();
c->Method2();
}
Out attribute parameter
// compile with: /clr:safe or /clr:pure
#include "stdafx.h"
using namespace System;
using namespace System::Runtime::InteropServices;
public ref class C1
{
public:
void Func([Out] String^% text)
{
text = "testing";
}
}
Use the FlagsAttribute
#include "stdafx.h"
using namespace System;
[ Flags ]
enum class Color
{
Red = 1,
Blue = 2,
Green = 4 // use powers of 2
};
int main()
{
Console::WriteLine("Colors: {0}, {1}, {2}", Color::Red, Color::Blue,Color::Green);
Console::WriteLine("Colors: {0:d}, {1:d}, {2:d}", Color::Red, Color::Blue,Color::Green);
Color c = Color::Red | Color::Blue;
String^ s1 = c.ToString("X");
Console::WriteLine( s1 );
String^ s2 = Enum::Format( Color::typeid, c , "G");
Console::WriteLine(s2 );
}