[英]C# interface function definition concrete implementation
如何实现在下面的界面中定义的功能? 当我在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 !!*/
}
}
创建一个通用interface IExample<T>
,然后使用具体的类型class Get : IExample<MyType>
来实现它,如下例所示。
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
{
// ...
}
丹尼斯的答案看起来像您想要的,但万一它不是,为了使您的代码正常工作,您可以这样做,但是我不确定这确实有多少价值...
public class Get : IExample
{
public T GetAnything<T>()
{
return default(T);
}
}
public void X()
{
var get = new Get();
var mt = get.GetAnything<MyType>();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.