The .NET reflection services allow you to discover, using APIs from the System.Reflection
namespace, the same information that you can see with the tools mentioned earlier. The key to this process is the type called System.Type
, which contains members that expose all of a type’s metadata. This is done with the help of other types from the System.Reflection
namespace
class A
{
public int val;
public int value
{
private set
{
val = value;
}
get
{
return val;
}
}
public A(int i)
{
this.val = i;
}
}
A a=new A(12);
Type t1 =typeof(A);
Type t2 = a.GetType();
Type t3=Type.GetType("A");
Console.WriteLine((t1 == t2) && (t1 == t3));//true
A aa=(A)Activator.CreateInstance(t1, 12);
t1.GetProperty("value").GetSetMethod(true)?.Invoke(aa, new object[] { 44 });
Console.WriteLine(t1.GetField("val").GetValue(aa));//44
Attributes
Attributes provide meta-information about assemblies, types, and members. This meta-information is consumed by the compiler, the CLR, or tools that use reflection services to read them. Attributes are actually types that derive from the System.Attribute
abstract class.
class DescriptionAttribute : Attribute
{
public string Text { get; private set; }
public bool Required { get; set; }
public DescriptionAttribute(string description)
{
Text = description;
}
}
[Description("Main component of the car", Required = true)]
class Engine
{
}
[AttributeUsage(AttributeTargets.Class|
AttributeTargets.Struct|
AttributeTargets.Method|
AttributeTargets.Property|
AttributeTargets.Field,
AllowMultiple = true,
Inherited = true)]
class DescriptionAttribute : Attribute
{
public string Text { get; private set; }
public bool Required { get; set; }
public DescriptionAttribute(string description)
{
Text = description;
}
}
[Serializable]
[Description("Main component of the car")]
[ComVisible(false)]
class Engine
{
}
[Serializable,
Description("Main component of the car"),
ComVisible(false)]
class Engine
{
}
Attributes In Reflections
var e = new Engine("M270 Turbo", 1600, 75.0);
var type = e.GetType();
var attributes = type.GetCustomAttributes(typeof(DescriptionAttribute),
true);
if (attributes != null)
{
foreach (DescriptionAttribute attr in attributes)
{
Console.WriteLine(attr.Text);
}
}
var properties = type.GetProperties();
foreach (var property in properties)
{
var pattributes =
property.GetCustomAttributes(
typeof(DescriptionAttribute), false);
if (attributes != null)
{
foreach (DescriptionAttribute attr in pattributes)
{
Console.WriteLine(
$"{property.Name} [{attr.Text}]");
}
}
}