Does D have class' attributes like C#'s?
Basile B.
b2.temp at gmx.com
Sat Dec 16 22:34:14 UTC 2017
On Saturday, 16 December 2017 at 21:11:43 UTC, Marc wrote:
> On Saturday, 16 December 2017 at 20:05:15 UTC, Anonymouse wrote:
>> On Saturday, 16 December 2017 at 19:57:30 UTC, Marc wrote:
>>> C# has a quite nice way to store metadata about a property by
>>> a feature called atributes[1]. For example, I can write
>>> something like this:
>>>
>>>> class A {
>>>> [TextSize(256)]
>>>> string Name { get; set; }
>>>> }
>>>
>>> So using runtime/reflection I can retrieve the TextSize value
>>> associated to A.name property.
>>>
>>> Does D have something similar?
>>
>> UDAs? User Defined Attributes.
>>
>> https://dlang.org/spec/attribute.html#UserDefinedAttribute
>> http://ddili.org/ders/d.en/uda.html
>>
>> class A {
>> @TextSize(256)
>> string name() { /* ... */ }
>> }
>
> I can't "pack" an object, right? In C#, TextSize is a class and
> 256 is constructor's first argument. In D it's pretty much an
> array but I guess it's close enough. Thanks!
No, it's either a struct or a class and it's not included in the
class itself.
You use the __trait(getAttributes) to retrieve the value when
needed:
```
struct TextSize {int value;}
class A {
@TextSize(256)
string name() { return ""; }
}
class B {
string name() { return ""; }
}
static assert(__traits(classInstanceSize, A) ==
__traits(classInstanceSize, B));
```
More information about the Digitalmars-d-learn
mailing list