比如:
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[]{ /* 形成一个枚举值,不会写 ! */ )
}
);
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[]{ /* 形成一个枚举值,不会写 ! */ )
}
);
{
public NetType TheType;
{
set{theType =value};
}
private NetType theType
}
(
"TheType",
BindingFlags.SetProperty,
null,
config.GetType().InvokeMember( null, BindingFlags.Public, null, null, null ),
new object[]{ /* 形成一个枚举值,不会写 ! */ )
}
);
这一段是有问题的。你先说这个方法要实现什么功能吧
Assembly assembly = Assembly.load( ....
assembly.GetType( "type string" )
Type[] l_typeArray = l_Assembly.GetTypes(); foreach (Type type in l_typeArray)
{
//取得方法名
MethodInfo l_method = type.GetMethod("TheType");
if (l_method != null)
{
//动态创建实例
object o = Activator.CreateInstance(type);
o.TheType = xxx
}
}
只能用config.GetType().GetProperty("TheType").PropertyType来得到类型,GetMember不行。
Type.GetType("config").GetProperty("TheType").SetValue(config,Enum.Parse(Type.GetType("NetType"),"telecom");
这样应该可以。
{
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();
}