读书人

反射达人请看:怎么根据名称使用反射

发布时间: 2012-03-03 15:33:03 作者: rapoo

反射达人请看:如何根据名称,使用反射设置一个枚举值?
比如:
enum NetType
{
unicom,
telecom
}

class Config
{
public NetType TheType;
{
get{return theType};
}
private NetType theType
}

现在我从配置文件中读出以下信息,
类名是config,属性名TheType,属性值telecom,属性类型:NetType

那么,我如何通过反射的方法,将Config的实例 config 的 TheType 字段值设置为 NetType.telecom 呢?

目前我的代码大致是这样的:

config.GetType().InvokeMember
(
"TheType ",
BindingFlags.SetProperty,
null,
config.GetType().InvokeMember( null, BindingFlags.Public, null, null, null ),
new object[]{ /* 形成一个枚举值,不会写 ! */ )
}
);

[解决办法]
try..

config.GetType().InvokeMember( "TheType ", BindingFlags.SetProperty, null, config, new object[] { Enum.Parse(typeof(NetType), "telecom ") });

[解决办法]
明白了,类名是config,属性名TheType,属性值telecom,属性类型:NetType都是从配置文件读出来的字符串。
Type.GetType( "config ").GetProperty( "TheType ").SetValue(config,Enum.Parse(Type.GetType( "NetType "), "telecom ");
这样应该可以。
[解决办法]
enum NetType
{
unicom,
telecom
}
class Config
{
public NetType TheType
{
set { theType = value; }
get { return theType; }
}
private NetType theType;
}

private void button1_Click(object sender, EventArgs e)
{
Config vConfig = new Config();
PropertyInfo vPropertyInfo = typeof(Config).GetProperty( "TheType ");
if (vPropertyInfo == null) return;
vPropertyInfo.SetValue(vConfig, Enum.Parse(typeof(NetType), "telecom "), null);

Text = vConfig.TheType.ToString();
}

读书人网 >C#

热点推荐