1

考虑这个结构:

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

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

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

谢谢!

4

2 回答 2

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;
于 2012-07-11T15:21:18.157 回答
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));
于 2012-07-11T15:05:12.207 回答