|
-
February 10th, 2005, 03:01 PM
#1
Using reflection to retrieve the default field value
Hello,
Using reflection, I'm trying to retrieve the default value for a field. In the code below, I would like to retrieve the value of 10. I can retrieve the name
of the field, its type and other meta-data, but I can't seem to retrieve the default value.
How do I do this?
Thanks,
Arjay
Code:
// Sample code from the internet
using System;
using System.Reflection;
class MyClass
{
publicint MyPublicInstanceField;
privateconstint MyPrivateConstField = 10;
}
class FieldAttributesExample
{
publicstaticvoid Main()
{
Type t = (typeof(MyClass));
string str;
FieldInfo[] fiAry = t.GetFields( BindingFlags.Static |
BindingFlags.Instance | BindingFlags.Public |
BindingFlags.NonPublic | BindingFlags.DeclaredOnly );
foreach (FieldInfo fi in fiAry)
{
Console.WriteLine("Field {0} is: ", fi.Name);
str = ((fi.Attributes & FieldAttributes.Static) != 0) ?
"Static" : "Instance";
Console.Write(str + " ");
str = ((fi.Attributes & FieldAttributes.Public) != 0) ?
"Public" : "Non-Public";
Console.Write(str + " ");
str = ((fi.Attributes & FieldAttributes.Literal) != 0) ?
"Literal" : String.Empty;
Console.WriteLine(str);
}
}
}
The output is:
Code:
Field MyPublicInstanceField is:
Instance Public
Field MyPrivateConstField is:
Static Non-Public
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|