2

我需要我的类的成员作为控件,并让它实现我们定义的接口。

如果我这样声明...

public class MyClass
{
    public Control MyMember;
}

...然后我没有得到接口方法,但是如果我这样声明它...

public class MyClass
{
    public IMyInterface MyMember;
}

...然后我没有得到控制方法。有没有办法指定 MyMember 必须初始化为继承自两者的类型?我在 MSDN 上找不到。就像是...

public class MyClass
{
    public Control : IMyInterface MyMember;
}

... 或者 ...

public class MyClass
{
    public Control MyMember : IMyInterface;
}

...除了这些都不起作用。我可以在声明成员时指定接口吗?如果可以,如何指定?

4

6 回答 6

2

您可以使用带有约束的泛型:

public interface MyClass {
    public T GetMyControl() where T : Control, IMyInterface { /* ........ */ }
}
于 2008-11-13T09:13:36.827 回答
1

由于围绕 Control 编写一个包装类和一个简单的泛型类非常麻烦:

public class MyGenericClass<T> where T : Control, IMyInterface
{
    public T t;
}

可能不符合您的需求。您可以简单地使用不同的属性以不同的方式访问该字段:

public class MyClass
{
    private IMyInterface m_field;
    public Control FieldAsControl
    {
        get { return m_field as Control; }
    }
    public IMyInterface Field
    {
        get { return m_field; }
        set
        {
            if (m_field is Control)
            {
                m_field = value;
            }
            else
            {
                throw new ArgumentException();
            }
        }
    }
}
于 2008-11-13T15:57:37.690 回答
0

您可以拥有从控件派生的自己的类,其接口定义如下:

class MyControl : Control, IMyInterface
{
}

然后使用这个类作为成员:

public class MyClass
{
    public MyControl MyMember;
}
于 2008-11-13T09:21:45.343 回答
0

声明一个接口 ISelf(of out T) [*],其中包括一个返回 T 的函数“Self”。让你的接口支持非泛型和泛型版本,其中泛型版本继承非泛型版本和 ISelf(of本身)。然后,您可以让一个类继承自 ISelf(of Control) 和 ISelf(of IMyInterface),并将您的字段 MyMember 声明为 ISelf(of IMyInterface(of Control)) 类型。然后可以将 MyMember 用作 iMyInterface,并将 MyMember.Self 用作控件。可以以这种方式组合任意数量的接口。

[*] 用于避免将尖括号作为 HTML 标记处理的泛型的 VB 语法。

于 2011-01-06T17:15:44.947 回答
-1

在接口上使用继承的力量

public interface IMyInterface : Control
{
  ..
}

现在你说你想要一个带有一些特殊方法的控件。


编辑: TcKs 当然是对的.. 你不能从具体类继承接口。

解决此问题的一种方法是使用返回控件的属性或方法来扩展接口。

样本:

public interface IMyInterface 
{
  Control Control { get; }

  [..rest of the definition..]
}

并像这样实现它:

class MyControl : Control, IMyInterface
{
  public Control Control { get { return this; } }

  [..rest of the implementation..]
}
于 2008-11-13T09:11:28.860 回答
-1

This sounds fundamentally wrong.

Does IMyInterface declare only the same methods/properties as found in the Control class? If not, what do you hope to accomplish? You cannot implement an interface and ignore the methods declared within it - you must explicitly write out the implementations.

If IMyInterface does, in fact, declare only the same methods/properties as found in the Control class, you will have to create your own MyControl class which inherits from Control and implements IMyInterface. This isn't some stupid quirk of the language. The Control class wasn't defined to be an IMyInterface and C# is a statically typed - not a "duck-typed" - language, so it cannot automatically give Control whatever interface you desire.

于 2008-11-13T17:47:01.230 回答