类都扩展了抽象类并实现了接口

时间:2009-04-25 18:49:39

标签: c# .net oop interface abstract-class

如果我有一个扩展抽象类并实现接口的类,例如:

,该怎么办?
class Example : AbstractExample, ExampleInterface
{
    // class content here
}

如何初始化此类,以便可以从接口和抽象类访问方法?

当我这样做时:

AbstractExample example = new Example();

我无法从界面访问方法。

5 个答案:

答案 0 :(得分:10)

你需要

  • 在AbstractExample
  • 中实现接口
  • 或获取对Example
  • 的引用

Example example = new Example();

答案 1 :(得分:6)

最后一个例子会将你绑定到一个接口或抽象类的实体实例,我认为这不是你的目标。坏消息是你不是在这里使用动态类型的语言,所以你坚持使用引用固定的“示例”对象,如先前的sprcified或cast / uncasting,即:

AbstractExample example = new Example();
((IExampleInterface)example).DoSomeMethodDefinedInInterface();

你的其他替代方法是让AbstractExample和I​​ExampleInterface都实现一个通用接口,这样你就可以了

abstract class AbstractExample : ICommonInterface
interface IExampleInterface : ICommonInterface
class Example : AbstractExample, IExampleInterface

现在您可以使用ICommonInterface并具有抽象类和IExample接口实现的功能。

如果这些答案都不可接受,您可能需要查看一些在.NET框架下运行的DLR语言,即IronPython。

答案 2 :(得分:5)

如果您只知道抽象类,则表明您通过Type实例了解实际类型。因此,您可以使用泛型:

private T SomeMethod<T>()
    where T : new(), AbstractExample, ExampleInterface
{
    T instance = new T();
    instance.SomeMethodOnAbstractClass();
    instance.SomeMethodOnInterface();
    return instance;
}

答案 3 :(得分:1)

使用:

Example example = new Example();

更多信息后更新:

如果您确定它实现了ExampleInterface,则可以使用

AbstractClass example = new Example();
ExampleInterface exampleInterface = (ExampleInterface)example;
exampleInterface.InterfaceMethod();

您还可以通过使用

检查界面来确保它真正实现它
if (example is ExampleInterface) {
    // Cast to ExampleInterface like above and call its methods.
}

我不相信Generics会帮助你解决编译时间问题,如果你只引用了AbstractClass,编译器就会抱怨。

编辑:欧文所说的或多或少。 :)

答案 4 :(得分:1)

我认为这个例子可以帮到你:

public interface ICrud
{
    void Add();
    void Update();
    void Delete();
    void Select();
}

public abstract class CrudBase
{
    public void Add()
    {
        Console.WriteLine("Performing add operation...");
        Console.ReadLine();
    }

   public void Update()
    {
        Console.WriteLine("Performing update operation...");
        Console.ReadLine();
    }
    public void Delete()
    {
        Console.WriteLine("Performing delete operation...");
        Console.ReadLine();
    }
    public void Select()
    {
        Console.WriteLine("Performing select operation...");
        Console.ReadLine();
    }
}

public class ProcessData : CrudBase, ICrud
{

}

var process = new ProcessData();
process.Add();