ここにはへの片方があります。これはほぼです。欠けているのは、リフレクションを使用することです。BindingFlags.FlattenHierarchyは、親クラスのプライベートメソッドを返しません。これらのタイプを保護されたものとして公開すると、これが解決されます。
// using System.Reflection
public IEnumerable<Type> GetTypesWithPropertyOfType(Assembly a, Type t)
{
BindingFlags propertyBindingFlags = BindingFlags.Public
| BindingFlags.NonPublic
| BindingFlags.Instance
| BindingFlags.FlattenHierarchy;
// a property is kept if it is assignable from the type
// parameter passed in
MemberFilter mf = (pi, crit)=>
(pi as PropertyInfo)
.PropertyType
.IsAssignableFrom(t);
// a class is kept if it contains at least one property that
// passes the property filter. All public and nonpublic properties of
// the class, and public and protected properties of the base class,
// are considered
Func<Type, bool> ClassFilter =
c=>c.FindMembers(MemberTypes.Property, propertyBindingFlags, mf, null)
.FirstOrDefault() != null;
// return all classes in the assembly that match ClassFilter
return
a.GetTypes()
.Where(c=>c.IsClass)
.Where(ClassFilter);
}
:(。あなたはまた、手動でトラバースベースクラスはプライベートメンバーを読み取ることができる)
あなたが与えられた型のプロパティを宣言アセンブリ内のすべてのタイプを見つけたい場合は、次のようなメソッドを書くことができ
定義する実行アセンブリ内のクラスを見つけるか、タイプtype1
のプロパティを継承するには、コールがあります
var v = GetTypesWithPropertyOfType(
Assembly.GetExecutingAssembly(),
typeof(type1));
foreach (var n in v) Console.WriteLine(n.FullName);
これは、foo1のを出力します。 FOOクラスを定義するコードがに改訂されている場合は(a)のfoo1.prop1
は、パブリックまたは保護された作りと、(b)foo1
からfoo2
継承し、上記のコードを印刷します:予想通り
foo1
foo2
foo3
を。
出典
2012-01-16 11:10:14
drf
「type1」のタイプのプロパティ値を取得するために上記のメソッドを変更するにはどうすればよいですか?私にお知らせください。私の意図は、クラスのインスタンスの値を取得することです。 – rinks
ねえ、私は努力をするにはあまりにも多くの努力をしていると思うので、私は別の解決策(非反射アプローチ)を得ました。しかし、助けてくれてありがとう。 – rinks