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

すべての型が既知の 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 に答える