簡體   English   中英

基於類型的條件邏輯

[英]conditional logic based on type

鑒於:

interface I
{
}

class B: I
{
}

class C: I
{
}

class A
{

    public void Method(B arg)
    {
    }

    public void Method(C arg)
    {
    }

    public void Method(I arg)
    {
       // THIS is the method I want to simplify.
       if (I is B)
       {
          this.Method(arg as B);
       }
       else if (I is C)
       {
          this.Method(arg as C);
       }
    }
}

我知道有更好的方法來設計這種類型的交互,但由於細節需要很長時間來解釋這是不可能的。 由於這種模式會重復多次,我想用一般的實現來替換條件邏輯,我只能使用一行。 我看不到實現這個泛型方法/類的簡單方法,但我的直覺告訴我它應該是可能的。

任何幫助,將不勝感激。

我將該方法放在接口中,然后讓多態決定調用哪個方法

interface I
{
   void Method();
}

class B : I
{
   public void Method() { /* previously A.Method(B) */}
}

class C : I
{
   public void Method() { /* previously A.Method(C) */ }
}

class A
{
   public void Method(I obj)
   { 
     obj.Method();
   }
}

現在,當您需要添加新類時,您只需要實現I.Method。 你不需要觸摸A.Method。

你想要的是雙重調度 ,特別是訪客模式

這有點難看,但它完成了工作:

public void Method(B arg)
{
  if (arg == null) return;
...
}
public void Method(C arg)
{
  if (arg == null) return;
...
}

public void Method(I arg)
{
  this.Method(arg as B);
  this.Method(arg as C);
}

不過,我不認為我會這樣做。 它實際上很痛苦地看着它。 對不起,我強迫大家看看這個。

interface I
{ 
} 

class B : I
{
}

class C : I
{
}    

class A 
{
    public void Method(B arg)
    {
        Console.WriteLine("I'm in B");
    }

    public void Method(C arg)
    {
        Console.WriteLine("I'm in C");
    }

    public void Method(I arg)
    {
        Type type = arg.GetType();

        MethodInfo method = typeof(A).GetMethod("Method", new Type[] { type });
        method.Invoke(this, new I[] { arg });
    }
}

它沒有以C#方便的形式存在 - 請參閱此處了解基於F#模式匹配的想法,它完全符合您的要求。 你可以用反射做一些事情來在運行時選擇重載,但這將非常慢,並且如果有任何事情滿足兩個重載,則會出現嚴重問題。 如果你有一個返回值,你可以使用條件運算符;

return (I is B) ? Method((B)I) : ((I is C) ? Method((C)I) : 0);

再次 - 不漂亮。

簡單。 在Visual Basic中,我一直使用CallByName執行此操作。

Sub MethodBase(value as Object)
    CallByName(Me, "RealMethod", CallType.Method, value)

這將調用最接近匹配運行時類型值的RealMethod的重載。

我確信您可以通過導入Microsoft.VisualBasic.Interaction或使用反射創建自己的版本來使用C#中的CallByName。

暫無
暫無

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

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