using reflection to read the value of a public static member

R

rettigcd

I have several classes that all have the same static member:

class A{
public static string Table = "TableA";
}

class B{
public static string Table = "TableB";
}

none of the classes inherit from a common base class or interface.

How can I use reflection to get the value stored in A.Table and
B.Table?
I found examples that called static member functions but none that
accessed non-function/non-property.

I'm simply trying associate a string with a class and not with a
particular instance of that class. I could create an interface but I
don't want to have to create an instance just to access a static
member.

thanks.
Dean
 
G

Guest

class someclass
{
public static string thing = "hey u!";

}
private void readvalue()
{
Type t = typeof(someclass);
System.Reflection.FieldInfo field= t.GetField("thing",
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Static);
MessageBox.Show("value is " + (string)field.GetValue(new
someclass()));
}

Abubakar.
 
R

rettigcd

Angel said:
Hi there... You can use the Type.GetMember method.
http://msdn.microsoft.com/library/d...f/html/frlrfsystemtypeclassgetmembertopic.asp
When specifying the binding flags remember to add BindingFlags.Static.

Regards,


--
Angel J. Hernández M.
MCP - MCAD - MCSD - MCDBA
http://groups.msn.com/desarrolladoresmiranda
http://www.consein.com

Angel,

I already tried using GetMember like this:

private static string GetTableName( Type t ){
MemberInfo[] TableNameInfo = t.GetMember("TableName" );
return TableNameInfo[0].ToString();
}

but the function returned: "string ClassName.TableName" instead of the
value stored in it.

So then I tried this:

private static string GetTableName( Type t ){
MemberInfo[] TableNameInfo =
t.GetMember("TableName",MemberTypes.All, BindingFlags.Static );

return TableNameInfo[0].ToString();

}

and got no members returned from the GetMembers() function.


After I get the MemberInfo object, how do I get the static value
associated with it. I was looking for a GetValue() function but
couldn't find one.

thanks,
Dean Rettig
 
R

rettigcd

Abubakar said:
class someclass
{
public static string thing = "hey u!";

}
private void readvalue()
{
Type t = typeof(someclass);
System.Reflection.FieldInfo field= t.GetField("thing",
System.Reflection.BindingFlags.Public |
System.Reflection.BindingFlags.Static);
MessageBox.Show("value is " + (string)field.GetValue(new
someclass()));
}

Abubakar.

:
Abubakar,

Thanks! This worked! But I don't want to create an instance of the
object so I changed it to:

MessageBox.Show( "value is " + (string)field.GetValue( null ) );

and it worked just fine.

Dean

 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top