簡體   English   中英

查找Interface實例后面的具體類型

[英]Finding the Concrete Type behind an Interface instance

簡而言之,我有一個C#函數,它對作為Object實例傳入的給定Type執行任務。 傳入類實例時,一切正常。但是,當對象被聲明為接口時,我真的很想找到具體的類並對該類類型執行操作。

這是無處不在的壞例子(金屬外殼不正確等等):

public interface IA
{
    int a { get; set; }
}
public class B : IA
{
    public int a { get; set; }
    public int b { get; set; }
}
public class C : IA
{
    public int a { get; set; }
    public int c { get; set; }
}

// snip

IA myBObject = new B();
PerformAction(myBObject);

IA myCObject = new C();
PerformAction(myCObject);

// snip

void PerformAction(object myObject)
{
    Type objectType = myObject.GetType();   // Here is where I get typeof(IA)
    if ( objectType.IsInterface )
    {
        // I want to determine the actual Concrete Type, i.e. either B or C
        // objectType = DetermineConcreteType(objectType);
    }
    // snip - other actions on objectType
}

我希望PerformAction中的代碼使用Reflection來反對它的參數,看看它不僅僅是IA的一個實例,而是它的B實例,並通過GetProperties()查看屬性“b”。 如果我使用.GetType(),我會得到IA的類型 - 而不是我想要的。

PerformAction如何確定IA實例的基礎Concrete Type?

有些人可能會建議使用Abstract類,但這只是我的壞例子的限制。 該變量最初將被聲明為接口實例。

Type objectType = myObject.GetType();

根據你的例子,還應該給你具體的類型。

你在做什么是真正的床設計,但你不必使用反射,你可以像這樣檢查它

void PerformAction(object myObject)
{
    B objectType = myObject as B;   // Here is where I get typeof(IA)
    if ( objectType != null )
    {
        //use objectType.b
    }
    else
    {
       //Same with A 
    }
    // snip - other actions on objectType
}

我必須同意糟糕的設計。 如果你有一個接口,那應該是因為你需要利用一些常見的功能而不關心具體的實現。 舉個例子,聽起來像PerformAction方法實際上應該是接口的一部分:

public interface IA
{
    int a { get; set; }
    void PerformAction();
}

public class B: IA
{
    public int a { get; set; }
    public int b { get; set; }

    public void PerformAction()
    {
        // perform action specific to B
    }
}

public class C : IA
{
    public int a { get; set; }
    public int c { get; set; }

    public void PerformAction()
    {
        // perform action specific to C
    }
}

void PerformActionOn(IA instance)
{
    if (instance == null) throw new ArgumentNullException("instance");

    instance.PerformAction();

    // Do some other common work...
}


B b = new B();
C c = new C();

PerformActionOn(b);
PerformActionOn(c);

您永遠不能擁有接口的實例。 因此,確定您是在處理接口還是具體類型是不可能的,因為您將始終處理具體類型。 所以我不確定你的問題是否有意義。 你究竟想做什么以及為什么?

也許你正在尋找is運營商

void PerformAction(object myObject)
{
    if (myObject is B)
    {
        B myBObject = myObject as B;
        myBObject.b = 1;
    }

    if (myObject is C)
    {
        C myCObject = myObject as C;
        myCObject.c = 1;
    }

    // snip - other actions on objectType
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM