[英]How to efficiently retrieve a specific class property value with similar named string as of property name
我有一个 class 结构,例如如下
public class ColorStuff
{
public Red Red { get; set; }
public Green Green { get; set; }
public Blue Blue { get; set; }
}
public class Red
{
public string Id { get; set; }
}
public class Green
{
public string Id { get; set; }
}
public class Blue
{
public string Id { get; set; }
}
我有如下方法通过颜色名称检索颜色 ID,如下所示
public string GetColorIdByName(string colorName)
{
var colorSettings = JsonConvert.DeserializeObject<ColorStuff>(content);
string colorId = string.Empty;
switch (colorName)
{
case "Red":
colorId = colorSettings.Red.Id;
break;
case "Green":
colorId = colorSettings.Green.Id;
break;
case "Blue":
colorId = colorSettings.Blue.Id;
break;
}
return colorId;
}
如您所见,对于每种颜色名称,我必须创建一个开关盒。 无论如何我可以在没有多个开关盒的情况下打电话吗?
例如,如果我想检索“绿色”的颜色 ID,我会访问“绿色”class 及其关联属性。 除了保持单独的开关盒外,还有其他有效的方法来实现这一点吗?
您可以为此目的使用反射。 例如,
var color = GetPropertyValue(colorSettings, colorName);
var id = GetPropertyValue(color, "Id");
或者
var id = GetPropertyValue(GetPropertyValue(colorSettings, colorName), "Id");
其中GetPropertyValue
定义为
public object GetPropertyValue(object instance ,string propertyName)
{
var objType = instance.GetType();
var prop = objType.GetProperty(propertyName);
return prop.GetValue(instance, null);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.