2012-07-11 117 views
1

考虑这样的结构:访问类名从属性名称

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

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

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

谢谢!

+0

不知道我是否关注。你的意思是,如果你有一个人的实例,例如Person.PersonName.FirstName ==“Bob”',那么你可以有一个方法'Person FindPersonByName(string name)'',喂入“Bob”,它会返回你先前分配了“Bob”的内存中的Person类的实例? – 2012-07-11 15:02:50

+0

或者你的意思是找到所有“类型”的引用,在其属性链中的某处声明一个名为“FirstName”的属性?就像'FindTypesWithPropertyName(“FirstName”)',它会返回'typeof(Name)'和'typeof(Person)'? – 2012-07-11 15:05:14

回答

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

很好的答案,但要小心:如果程序集中有多个类型具有该名称的属性,则从types.First()返回的类型可能不是您期望的类型。如果所有类型的所有属性都有唯一的名称,这不是问题。 – Andy 2012-07-11 15:30:13

+0

你说得对。谢谢。 – 2012-07-11 15:32:14

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;