2

我有一个名为的基类Graph和一个名为IDataTip.

我有许多实现这两个的类,例如:

class TreeGraph : Graph, IDataTip
{
  //interface implementation
}

我想知道是否有办法声明另一个类的成员,使得成员的类型需要与抽象类和接口匹配的类

例如,在以下类中:

class GraphExporter
{
    public Object GraphWithDataTip {set; get;}
}

我希望能够Object用指示GraphWithDataTip应该继承Graph和实现的东西替换类型IDataTip。有没有办法做到这一点?或者如果没有,有人可以推荐一个更明智的设计吗?

提前致谢!

4

4 回答 4

6

您可以使用通用约束

public class FooClass<T> where T: Graph, IDataTip
{
    public T Foo { get; set; }
}
于 2012-09-04T13:01:16.213 回答
4

听起来好像您想要:

  • abstract class thing : Graph, IDataTip用于您的参数的新基本类型 ( )
  • 形式的通用方法void MyMethod<T>(T thing) where T : Graph, IDataTip

或者,您可以在方法中强制转换参数并在不合适时抛出异常,但这将是仅运行时检查。

于 2012-09-04T13:02:05.260 回答
0

您可以定义 Graph 和 IDataTip 都实现的接口,然后让另一个类的成员成为该新接口的实例。

//new interface
interface IGraphAndDataTip
{
}

class Graph : IGraphAndDataTip
{
}

interface IDataTip : IGraphAndDataTip
{
}

class AnotherClass
{
    //implements both graph and IDataTip
    IGraphAndDataTip MyMember;
}
于 2012-09-04T13:02:23.820 回答
0

我假设您的意思是基类的派生类?你是这个意思吗?

public abstract class Graph {
    public abstract void SomeMethod();
}

public interface IDataTip {
    void SomeMethod();
}

public class MyClassDerivedFromGraph: Graph, IDataTip {
    void SomeMethod() {
       // This method matches both the interface method and the base class method.
    }
}
于 2012-09-04T13:03:51.430 回答