C# 从属性名访问类名
考虑一下这种结构:C# 从属性名访问类名,c#,.net,reflection,types,system.reflection,C#,.net,Reflection,Types,System.reflection,考虑一下这种结构: Name { public string FirstName { get; set; } } Person { public Name PersonName { get; set; } } 我将FirstName属性的名称作为字符串。现在我想使用这个字符串“FirstName”在运行时获取Person类的名称。我不确定这是否可行。有人知道实现这一目标的方法吗 谢谢 如果所有类型都在已知的一个或多个程序集中,则可以在程序集中搜索: var types = A
Name
{
public string FirstName { get; set; }
}
Person
{
public Name PersonName { get; set; }
}
我将FirstName
属性的名称作为字符串。现在我想使用这个字符串“FirstName”在运行时获取Person
类的名称。我不确定这是否可行。有人知道实现这一目标的方法吗
谢谢 如果所有类型都在已知的一个或多个程序集中,则可以在程序集中搜索:
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));
这是一个非常奇怪的要求。也就是说,你可以这样做:
// 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。定义您的类型范围。
//如果你不知道从哪里开始,你可以尝试所有的方法
//已加载到应用程序域中的类型。
var allTypes=来自AppDomain.CurrentDomain.GetAssemblys()中的程序集
来自程序集中的类型。GetTypes()
选择类型;
// 2. 搜索每种类型并查找具有公共
//名为“FirstName”的属性(在您的示例中为`Name`类型)。
var typesWithFirstNameProp=新哈希集
(
从所有类型中的类型
其中type.GetProperty(“FirstName”)!=null
选择类型
);
// 3. 搜索每种类型并找到至少有一种的类型
//其类型与找到的类型之一匹配的公共属性
//在第2步中(在您的案例中:Person类型)。
var result=来自所有类型中的类型
让propertyTypes=type.GetProperties().Select(p=>p.PropertyType)
其中typesWithFirstNameProp.重叠(propertyTypes)
选择类型;
不确定我是否遵循。你的意思是如果你有一个Person的实例,比如Person.PersonName.FirstName==“Bob”
,那么在某个地方你可以有一个方法Person FindPersonByName(string name)
,输入“Bob”,它将返回给你内存中分配了“Bob”的Person
类的实例以前?或者您的意思是找到对所有“类型”的引用,这些类型在其属性链中的某个位置声明了一个名为“FirstName”的属性?类似于FindTypesWithPropertyName(“FirstName”)
的东西,它将同时返回typeof(Name)
和typeof(Person)
?回答得好,但要注意一点:如果程序集中有多个类型具有该名称的属性,则从types.First()返回的类型可能不是您期望的类型。如果所有类型的所有属性都有唯一的名称,这不是问题。