簡體   English   中英

C#從基類隱式轉換為擴展(System.Reflection.Assembly)

[英]C# implicit cast from base class to extended (System.Reflection.Assembly)

我一直在從事提到c-sharp-compilerresults-generateinmory的項目

我一直在寫很多代碼來實現“類發現”。 它很酷,但是我意識到如果將所有東西都實現為System.Reflection.Assembly的派生類,效率會更高。

因此,在編寫新的派生類時,我遇到了一個問題。 當我嘗試將基類分配給新的派生類時,它將引發錯誤,只是正常情況下did you miss an explicit cast錯誤。

我以為C#是否對擴展類型進行隱式轉換?

所以我有一些像這樣的源代碼...

Assembly asm = MyCompilerResults.CompiledAssembly(); /* this works */
Interface asmInterface = new Interface();
asmInterface = asm; /* bad */
asmInterface = (Interface)asm; /* bad */


public class Interface : Assembly {
    public Interface() {} // I always just declare the empty constructor.

    public void Helpermethod1() {}
    public void Helpermethod2() {}
    public void Helpermethod3() {}
};

因此,這只是我編寫C#的第二周,我不得不問...
如何將基類添加到類中?

這里的問題... 為什么不能在C#中從基類向派生類編寫隱式運算符?
這似乎表明,除非我誤解了答案,否則我的投射應該可以工作。

您可能想在這里完成一些不同的事情,這可以通過使用擴展方法來完成

您必須創建一個靜態類,然后該類提供了擴展對象的功能,如下所示:

public static class AssemblyExtension
{

    public static void HelperMethod1(this Assembly asm)
    {
        Console.WriteLine(asm.ToString());
    }
}

然后可以這樣稱呼它:

Assembly asm = MyCompilerResults.CompiledAssembly(); 
asm.HelperMethod1();

我想你誤會了一些東西。 您試圖實現的是將基類分配給派生類。 幾乎不可能在所有情況下都如此。

考慮以下幾點:

public class A 
{
}

public class B : A
{
}

A a = new B();

// some code

B b = (B)a; // it is possible. Behind the scenes, variable a is of B type.

但:

A a = new A();
B b = (B)a; //IT'S NOT ALLOWED. The variable a is of type A that has 
            // no "knowledge" about B class.

在您的情況下, CompiledAssembly()返回的Assembly實例不包含有關Interface類的任何信息,因此無法直接轉換。

有兩種選擇。 寫包裝器:

public class Interface 
{
     private readonly Assembly underlyingAssembly;
     publiic Interface(Assembly asm)
     {
        this.underlyingAssembly = asm;
     }

     // other methods
}

Assembly someAsm = MyCompilerResults.CompiledAssembly();
Interface interface = new Interface(someAsm);

或編寫擴展方法:

public static class AsmExt
{
     public static void SomeMethod(this Assembly asm)
     {
     }
}

Assembly someAsm = MyCompilerResults.CompiledAssembly();
someAsm.SomeMethod();

暫無
暫無

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

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