【问题标题】:C# interface function definition concrete implementationC#接口函数定义具体实现
【发布时间】:2012-04-13 20:12:36
【问题描述】:

如何实现下面接口中定义的功能?当我在 VS2010 中实现时,如下所示。 MyType 变灰并且不再识别类型?谢谢!

public interface IExample
{
  T GetAnything<T>();
}

public class MyType
{
  //getter, setter here
}

public class Get : IExample
{
 public MyType GetAnything<MyType>()
 {      ^^^^^^^            ^^^^^^
   MyType mt = new MyType();
   ^^^^^^^^^^^^^^^^^^^^^^^^^^    /* all greyed out !!*/
 }
}

【问题讨论】:

标签: c# generics interface implementation


【解决方案1】:

创建一个通用 interface IExample&lt;T&gt;,然后使用具体类型 class Get : IExample&lt;MyType&gt; 实现它,如下例所示。

public interface IExample<T> where T : new()
{
    T GetAnything();
}

public class Get : IExample<MyType>
{
    public MyType GetAnything()
    {
        MyType mt = new MyType();
        return mt;
    }
}

public class MyType
{
    // ...
}

【讨论】:

  • 方法的类型参数T隐藏了接口的类型参数T;他们有相同的名字,但他们是独立的。
  • @phoog 是的,谢谢。但我认为您可以删除该方法的类型参数。相应地更新了我的代码示例。
  • 你在接口声明中忘记了 where T: new();)
  • 是的,我认为这就是您的意图。 OP 是否试图将同质的IExample&lt;T&gt;s 存储在单个集合中还有待观察;这通常是人们想要的,当然这会使事情变得有些复杂。
  • @RaphaëlAlthaus 几分钟前已经添加。不过还是谢谢。这些是我在没有编译器的情况下编写代码时总是错过的细节。一旦粘贴到VS中,就很明显了。
【解决方案2】:

Dennis 的答案看起来像您想要的,但万一不是,为了让 您的 代码正常工作,您可以这样做,但我是不知道这到底有多少价值……

public class Get : IExample
{
    public T GetAnything<T>()
    {
        return default(T);
    }
}

public void X()
{
    var get = new Get();
    var mt = get.GetAnything<MyType>();
}

【讨论】:

    猜你喜欢
    • 2016-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多