C# 使用字符串获取第二层类类型
目前我有一个“字段”类型,里面有很多属性。我通过以下方式获得所需的属性:C# 使用字符串获取第二层类类型,c#,.net,C#,.net,目前我有一个“字段”类型,里面有很多属性。我通过以下方式获得所需的属性: public object this[string propertyName] { get { Type myType = typeof(Fields); PropertyInfo myPropInfo = myType.GetProperty(propertyName); return myPropInfo.GetValue(this, null);
public object this[string propertyName]
{
get
{
Type myType = typeof(Fields);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
return myPropInfo.GetValue(this, null);
}
set
{
Type myType = typeof(Fields);
PropertyInfo myPropInfo = myType.GetProperty(propertyName);
myPropInfo.SetValue(this, value, null);
}
}
当需要一个简单的类型时,例如字符串,哪些功能很好:
public void UpdateData(string location, string data){
Fields dataUpdate = new Fields();
dataUpdate[location] = data;
ComHandler.SendDataUpdate(dataUpdate);
}
我需要知道如何为非字符串的实例获取此“dataUpdate[location]”的类型。我试过使用
typeof(dataUpdate[location])
if(dataUpdate[location] is CustomField)
//do work
else
//is a string
但是找不到任何资源来让它工作
编辑答案
最后,我使用try-catch语句来确定该项基于什么类型,是可以转换为CustomField,还是仅仅是一个字符串。wow,请您补充一下这种方法的用途好吗?为什么
dataUpdate[“location”]
而不是dataUpdate.location
?if(dataUpdate[location]?.GetType()==typeof(CustomField))
?如果返回的值为null,则不起作用。@SergeyBerezovskiy dataUpdate.Location不存在,这是一个字符串,用于标识需要设置为数据的字段的witch属性value@vipersassassin它应该存在。否则,myType.GetProperty(propertyName)
将返回null
@RenéVogt我刚刚尝试了你的建议,但似乎也不起作用。