C#子类同时保持名称。深伏都教?

时间:2012-06-01 15:00:46

标签: c# .net c#-3.0

我有一个我正在使用的dll,它包含一个类foo.Launch。我想创建另一个子类Launch的dll。问题是类名必须相同。这被用作另一个软件和foo.Launch类的插件,它是启动插件的敌人。

我试过了:

namespace foo
{
    public class Launch : global::foo.Launch
    {
    }
}

using otherfoo = foo;
namespace foo
{
    public class Launch : otherfoo.Launch
    {
    }
}

我也尝试在引用属性中指定别名,并在我的代码中使用该别名而不是全局,这也不起作用。

这两种方法都不起作用。有没有办法可以在using语句中指定要查看的dll名称?

4 个答案:

答案 0 :(得分:6)

您需要为原始程序集添加别名,并使用extern alias引用新程序集中的原始程序集。以下是使用别名的示例。

extern alias LauncherOriginal;

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace foo
{
    public class Launcher : LauncherOriginal.foo.Launcher
    {
        ...
    }
}

这是一个walkthrough,解释了如何实现它。

另外,你提到你之前尝试使用别名并遇到问题,但你没有说出它们是什么,所以如果这不起作用那么请提出错误。

答案 1 :(得分:2)

正如Chris所说,你可以在原始程序集上使用别名。

如果你不能那样,那么你可以通过使用第三个集会来作弊

Assembly1.dll(您的原创)

namespace foo { 
     public class Launch {}
}

Assembly2.dll(虚拟)

namespace othernamespace { 
     public abstract class Dummy: foo.Launch {}
}

Assembly3.dll(你的插件)

namespace foo{ 
     public class Launch: othernamespace.Dummy{}
}

我对此并不感到自豪!

答案 2 :(得分:0)

如果类名在另一个名称空间中定义,则它可以是相同的,但它让人难以理解为什么有人想要自己这样做。

答案 3 :(得分:0)

也许你需要使用extern别名。

例如:

//in file foolaunch.cs

using System;

namespace Foo
{
    public class Launch
    {
        protected void Method1()
        {
            Console.WriteLine("Hello from Foo.Launch.Method1");
        }
    }
}

// csc /target:library /out:FooLaunch.dll foolaunch.cs

//now subclassing foo.Launch

//in file subfoolaunch.cs

namespace Foo
{
    extern alias F1;
    public class Launch : F1.Foo.Launch
    {
        public void Method3()
        {
            Method1();
        }
    }
}


// csc /target:library /r:F1=foolaunch.dll /out:SubFooLaunch.dll subfoolaunch.cs

// using
// in file program.cs

namespace ConsoleApplication
{
    extern alias F2;
    class Program
    {
        static void Main(string[] args)
        {
            var launch = new F2.Foo.Launch();
            launch.Method3();
        }
    }
}

// csc /r:FooLaunch.dll /r:F2=SubFooLaunch.dll program.cs