【问题标题】:Accessing Class Name from Property Name从属性名访问类名
【发布时间】:2012-07-11 14:56:30
【问题描述】:

考虑这个结构:

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

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

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

谢谢!

【问题讨论】:

  • 不确定我是否关注。您的意思是,如果您有一个 Person 实例,例如 Person.PersonName.FirstName == "Bob",那么您可以在某个地方拥有一个方法 Person FindPersonByName(string name),输入“Bob”,它将返回分配给您的内存中 Person 类的实例“鲍勃”以前?
  • 或者您的意思是找到对在其属性链中某处声明名为“FirstName”的属性的所有“类型”的引用?像FindTypesWithPropertyName("FirstName") 这样的东西会返回typeof(Name) 和typeof(Person)?

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


【解决方案1】:

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

// 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;

【讨论】:

    【解决方案2】:

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

    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));
    

    【讨论】:

    • 好答案,但要注意一点:如果程序集中有多个类型具有该名称的属性,则从 types.First() 返回的类型可能不是您期望的类型。如果所有类型的所有属性都有唯一的名称,这不是问题。
    猜你喜欢
    • 2011-10-15
    • 2016-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多