从属性名称访问类名

时间:2012-07-11 14:56:31

标签: c# .net reflection types system.reflection

考虑这个结构:

Name
{
    public string FirstName { get; set; }
}

Person
{
    public Name PersonName { get; set; }
}

我将FirstName属性的名称作为字符串。现在我想使用此字符串“FirstName”在运行时获取Person类的名称。我不确定这是否可行。有谁知道实现这个目标的方法?

谢谢!

2 个答案:

答案 0 :(得分:2)

这是一个非常奇怪的要求。那就是说,你可以这样做:

// 1. Define your universe of types. 
//    If you don't know where to start, you could try all the  
//    types that have been loaded into the application domain.
var allTypes = from assembly in AppDomain.CurrentDomain.GetAssemblies()
               from type in assembly.GetTypes()
               select type;

// 2. Search through each type and find ones that have a public  
//    property named "FirstName" (In your case: the `Name` type).    
var typesWithFirstNameProp = new HashSet<Type>
(
        from type in allTypes
        where type.GetProperty("FirstName") != null
        select type
);


// 3. Search through each type and find ones that have at least one 
//    public property whose type matches one of the types found 
//    in Step 2 (In your case: the `Person` type).
var result = from type in allTypes
             let propertyTypes = type.GetProperties().Select(p => p.PropertyType)
             where typesWithFirstNameProp.Overlaps(propertyTypes)
             select type;

答案 1 :(得分:1)

如果所有类型都在已知的一个或多个程序集中,则可以在程序集中进行搜索:

var types = Assembly.GetExecutingAssembly().GetTypes();
var NameType = types.First(t => t.GetProperty("FirstName") != null);
var PersonType = types.First(t => t.GetProperties.Any(pi => pi.MemberType = NameType));