你没有张贴要求很多信息,但是,如果你知道你的对象类型,然后就没有必要使用反射,你可以用is
像测试这样的:
if(returnCity && myObject is Country) //I'm assuming that the input value is boolean but, you get the idea...
{
return myObject.City.Name;
}
else
{
return myObject.Name;
}
现在,如果你想使用反射,你可以做这些线路中的东西:
public static string GetNameFrom(object myObject)
{
var t = myObject.GetType();
if(t == typeof(Country))
{
return ((Country)myObject).City.Name;
}
return ((City)myObject).Name;
}
或者,更通用的方法:
static string GetNameFrom(object myObject)
{
var type = myObject.GetType();
var city = myObject.GetProperty("City");
if(city != null)
{
var cityVal = city.GetValue(myObject, null);
return (string)cityVal.GetType().GetProperty("Name").GetValue(cityVal, null);
}
return (string)type.GetProperty("Name").GetValue(myObject, null);
}
可以告诉你输入的输出如何影响?你的意见是什么? –
的Cuong乐,当 “myCountry.Name”,然后 “{国家}。{NAME}”,当 “myCountry.MyCity.Name”,然后 “{国家}。{MyCity}。{NAME}”,并使其SENS? – Yara
更好告诉你的方法定义什么是你输入的,什么是我们的输出 –