[英]C# interface function returning class depending on where it gets implemented
I would like to have a Interface that depending on what class implements it, a function that the interface declares should return a specific class.我想要一个接口,这取决于 class 实现它的方式,接口声明的 function 应该返回特定的 class。
should i use something like this?我应该使用这样的东西吗?
public interface IMyInterface
{
T returnClassInstance();
}
and how should it look when i want to implement it into the classes?当我想在类中实现它时它应该是什么样子?
public class MyClass : IMyInterFace
{
public T returnClassInstance()
{
ClassInstance class = new ClassInstance();
return (T)class;
}
}
What is the best approach to something like this?解决此类问题的最佳方法是什么?
You can use generics in interfaces -您可以在接口中使用 generics -
public interface IMyInterface<T>
{
T returnClassInstance();
}
And while implementing this interface in class, just use the specific class in generic在 class 中实现此接口时,只需在通用中使用特定的 class
public class MyClass : IMyInterface<ClassInstance>
{
public ClassInstance returnClassInstance()
{
ClassInstance obj = new ClassInstance();
return obj;
}
}
Generics Generics
public interface IMyInterface<T>
{
T returnClassInstance();
}
public class MyClass : IMyInterFace<ClassInstance>
{
public ClassInstance returnClassInstance()
{
ClassInstance class = new ClassInstance();
return class;
}
}
You can declare it like so:您可以像这样声明它:
public interface IMyInterface<T>
{
T ReturnClassInstance();
}
and implement it:并实施它:
public class MyClass : IMyInterface<MyClass>
{
public T ReturnClassInstance()
{
return this;
}
}
You are looking for the Class Factory pattern.您正在寻找Class 工厂模式。 Here is a good CodeProject article about it.这是一篇很好的CodeProject 文章。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.