私は受け入れる方法があります IEnumerable<dynamic>
メソッド内の動的タイプをテストして、特定のインターフェイスを実装しているかどうかを確認する方法はありますか?
私の意図は次のようなものです:
public void myMethod(IEnumerable<dynamicT> enumerable)
{
if (dynamicT is IInterface)
{
// do one thing
}
else if (dynamicT is IAnotherInterface)
{
// do another thing
}
}
更新
私はこの重要な事実を含めるべき<T>
でした:動的です。
許してください、それは私がコーディングしているところから真夜中に近づいています。:-$
is
キーワードは、のためにあるオブジェクトながら反射をするために必要とされているタイプ。
を使用typeof(T).GetInterfaces()
して、特定のタイプに適用されているすべてのインターフェースをプルできます。
public void MyMethod(IEnumerable<T> enumerable)
{
var typeInterfaces = typeof(T).GetInterfaces();
if (typeInterfaces.Contains(typeof(IInterface))) {
// Something
}
else if(typeInterfaces.Contains(typeof(IAnotherInterface))) {
// Something Else
}
}
============コメントに基づく更新============
Tが動的である場合、Tは任意の数の異なるタイプを同時に表す可能性があるため、タイプ自体から探している情報を取得することはできません。
ただし、各要素をループして、is
キーワードを使用してオブジェクト自体をテストすることはできます。
public static void MyMethod<T>(IEnumerable<T> enumerable)
{
foreach (var dynObj in enumerable)
{
var typeInterfaces = dynObj.GetType().GetInterfaces();
if (typeInterfaces.Contains(typeof(IInterface))) {
// Something
}
else if(typeInterfaces.Contains(typeof(IAnotherInterface))) {
// Something Else
}
}
}
または、列挙可能なすべての可能なインターフェイスをテストしたいだけの場合は、次のようにすることができます。
public static void MyMethod<T>(IEnumerable<T> enumerable)
{
var allInterfaces = enumerable.SelectMany(e => e.GetType().GetInterfaces()).ToList();
if (allInterfaces.Contains(typeof(ITheFirstInterface)))
{
Console.WriteLine("Has The First Interface");
}
if (allInterfaces.Contains(typeof(ITheSecondInterface)))
{
Console.WriteLine("Has The Second Interface");
}
}
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加