簡體   English   中英

靜態上下文和派生類型中的C#擴展方法

[英]C# Extension methods in static contexts and derived types

需要使用一些新方法擴展C#中的現有類型,以便滿足以下條件:

  1. 擴展方法應該抵抗另一個組裝
  2. 它們應該看起來像原始類型的靜態方法
  3. 它們也應該對原始類型的派生類的實現者可見

示例,程序集Orig.dll:

public class Orig {
    public static void Method1() { }
}

程序集Extend.dll:

// method, which extends Orig in a static context is needed ...  
// ?? 
// public static void Method2() { } 

用法示例(理想):

public class Usage : Orig {
   Method1();  // naturally working
   Method2();  // <- this is needed
}
public void SomeFunc() {
   Orig.Method2();  // <- this should ideally work also 
}    

自然而然地想到的第一個嘗試是使用C#3.0的擴展方法。 但不像我想要的那樣,這些(我認為)只適用於被擴展類型的實例 在派生類的上下文中,這可以像下面那樣得到滿足:

public class Usage : Orig {
   Method1();  // naturally working
   this.Method2();  // working with C# 3.0 extension methods, but clumsy syntax
}

第一個要求(來自裝配外部的靜態上下文)似乎根本不是完全可填充的? 那么還有另一種潛在的方法嗎?

@Edit:我可能沒有清楚地描述這個問題。 需求在以下代碼段中被注釋掉(因為它們不適用於常見的C#擴展方法)。 所以我嘗試找到另一種方法,啟用超出評論的語法:

    // having a class 
public class Orig { }

// which is extended with some functions (from another assembly)
public static class ExtOrig {
    public static void ExtMeth (this Orig orig, string bla) {}
}

// derived classes should DIRECTLY!! see the extension
public class Derived : Orig {
    public void MyMethod() {
        // ExtMeth("inside orig"); <- does not work
        this.ExtMeth("this derived");  // <- this keyword needed
    }
    // for static methods even worse: 
    public static void MyMethod2() {
        // ExtMeth("inside orig"); <- does not work
        // this.ExtMeth("this derived");  // <- 'this' not usable here :(
    }
}
// for shorter syntax, static access would be needed 
public class SomeClass {

    private void SomeFunc() {
        // Orig.ExtMeth("static orig"); <- does not work
        new Orig().ExtMeth("outside orig"); // <- instance needed :(

        // Derived.ExtMeth("static derived"); <- does not work
        new Derived().ExtMeth("outside derived"); 
    }
}
  1. 擴展方法可以與包含要擴展類型的程序集分開存在於單獨的程序集中。 擴展組件只需要引用原始組件。 其他程序集中的任何客戶都只需引用原始程序集和擴展程序集。

  2. 擴展方法不能作為擴展類型的靜態方法出現。 它們只能作為實例方法出現。 社區中已經討論過需要靜態擴展方法和可能的實現,但據我所知,MS尚未承諾將此功能添加到C#中。

  3. 擴展方法(具有適當的可見性)對於兩種派生類型以及這些派生類型的任何使用者都是可見的。

擴展方法或局部類不會幫助您。 嘗試使用Singleton設計模式,因為這可能會為您提供使用實例而非靜態成員所需的行為

暫無
暫無

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

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