I have such a class
[Description("This is a wahala class")]
public class Wahala
{
}
Is there anyway to get the content of the Description
attribute for the Wahala
class?
Your class object needs to define __init__(self) and x needs to be self. x=1. Then assign t = T() and use print(vars(t)) and it will show you a dictionary of all the class attributes.
Class attributes are the variables defined directly in the class that are shared by all objects of the class. Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor. Defined directly inside a class.
First, declare an instance of the attribute you want to retrieve. Then, use the Attribute. GetCustomAttribute method to initialize the new attribute to the value of the attribute you want to retrieve. Once the new attribute is initialized, you simply use its properties to get the values.
Use dot notation or setattr() function to set the value of class attribute. Python is a dynamic language. Therefore, you can assign a class variable to a class at runtime. Python stores class variables in the __dict__ attribute.
Absolutely - use Type.GetCustomAttributes
. Sample code:
using System;
using System.ComponentModel;
[Description("This is a wahala class")]
public class Wahala
{
}
public class Test
{
static void Main()
{
Console.WriteLine(GetDescription(typeof(Wahala)));
}
static string GetDescription(Type type)
{
var descriptions = (DescriptionAttribute[])
type.GetCustomAttributes(typeof(DescriptionAttribute), false);
if (descriptions.Length == 0)
{
return null;
}
return descriptions[0].Description;
}
}
The same kind of code can retrieve descriptions for other members, such as fields, properties etc.
Use reflection and Attribute.GetCustomAttributes
http://msdn.microsoft.com/en-us/library/bfwhbey7.aspx
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With