使用通用方法实现接口
我在这个上画了一个空白,看起来似乎找不到以前编写的任何示例。我试图实现一个类的通用接口。当我实现接口时,我认为有些东西不能正常工作,因为Visual Studio会不断产生错误,说我没有实现通用接口中的所有方法。使用通用方法实现接口
这里是我工作的一个存根:
public interface IOurTemplate<T, U>
{
IEnumerable<T> List<T>() where T : class;
T Get<T, U>(U id)
where T : class
where U : class;
}
那么应该怎么我的课是什么样子?
你应该返工你的界面,就像这样:
public interface IOurTemplate<T, U>
where T : class
where U : class
{
IEnumerable<T> List();
T Get(U id);
}
然后,你可以实现它作为一个泛型类:
public class OurClass<T,U> : IOurTemplate<T,U>
where T : class
where U : class
{
IEnumerable<T> List()
{
yield return default(T); // put implementation here
}
T Get(U id)
{
return default(T); // put implementation here
}
}
或者,你可以具体实现:
public class OurClass : IOurTemplate<string,MyClass>
{
IEnumerable<string> List()
{
yield return "Some String"; // put implementation here
}
string Get(MyClass id)
{
return id.Name; // put implementation here
}
}
我想你可能要重新定义你的界面是这样的:
public interface IOurTemplate<T, U>
where T : class
where U : class
{
IEnumerable<T> List();
T Get(U id);
}
我想你想的方法来使用(再利用),其中他们宣布通用接口的通用参数;而且你可能不想用它们自己的(不同于接口的)泛型参数来生成泛型方法。
鉴于接口,因为我重新定义它,你可以这样定义一个类:
class Foo : IOurTemplate<Bar, Baz>
{
public IEnumerable<Bar> List() { ... etc... }
public Bar Get(Baz id) { ... etc... }
}
或定义一个通用类是这样的:
class Foo<T, U> : IOurTemplate<T, U>
where T : class
where U : class
{
public IEnumerable<T> List() { ... etc... }
public T Get(U id) { ... etc... }
}
您也可以将其实现为一个通用类,即:class Foo
你说得对,我会补充一点。 – ChrisW 2009-08-28 02:31:14
- 编辑
的其他答案更好,但是请注意,如果你对它的外观感到困惑,你可以让VS为你实现接口。
下面描述的过程。
好时,Visual Studio告诉我,它应该是这样的:
class X : IOurTemplate<string, string>
{
#region IOurTemplate<string,string> Members
IEnumerable<T> IOurTemplate<string, string>.List<T>()
{
throw new NotImplementedException();
}
T IOurTemplate<string, string>.Get<T, U>(U id)
{
throw new NotImplementedException();
}
#endregion
}
注意,我所做的就是写界面,然后点击它,然后等待的小图标,弹出有VS生成实施我:)
参见:尽管你在接口中专门设计了'T'和'U'(它们都是'string'),这些方法本身是通用的,它们有自己独立/不同的泛型参数......这可能不是OP意。 – ChrisW 2009-08-28 02:26:00
我同意,我认为你的建议很好,我只是展示了如何让VS为你实现接口,如果你对它的外观感到困惑的话。 – 2009-08-28 02:27:58
错误的问题标题。在普通的类和接口中有通用的方法,并且有方法的通用接口。 – Kobor42 2014-03-14 06:13:58