Ale*_*mes 0 .net c# reflection
我出于某种原因试图使用反射,我遇到了这个问题.
class Service
{
public int ID {get; set;}
.
.
.
}
class CustomService
{
public Service srv {get; set;}
.
.
.
}
//main code
Type type = Type.GetType(typeof(CustomService).ToString());
PropertyInfo pinf = type.GetProperty("Service.ID"); // returns null
Run Code Online (Sandbox Code Playgroud)
我的问题是我想在主要对象的另一个属性中获得一个属性.有这个目标的简单方法吗?
提前致谢.
您需要首先获得对该srv属性的引用,然后ID:
class Program
{
class Service
{
public int ID { get; set; }
}
class CustomService
{
public Service srv { get; set; }
}
static void Main(string[] args)
{
var serviceProp = typeof(CustomService).GetProperty("srv");
var idProp = serviceProp.PropertyType.GetProperty("ID");
var service = new CustomService
{
srv = new Service { ID = 5 }
};
var srvValue = serviceProp.GetValue(service, null);
var idValue = (int)idProp.GetValue(srvValue, null);
Console.WriteLine(idValue);
}
}
Run Code Online (Sandbox Code Playgroud)