I wrote a very simple class taking a generic parameter, say T
. Now, I want to enforce that T
can be only one of my custom types ClassA
, ClassB
and ClassC
, so that I cannot mistakenly use it with meaningless types like int
, long
or even other classes I wrote. I thought that a way to do this would be开发者_运维知识库 making those three classes implement the same, empty ISomething
interface and using a where T : ISomething
in the generic class definition. However, I don't know if this approach (implementing an empty interface) makes any sense. Is there any better way to do this?
This is not going to work. As T
is of type ISomething
, you only have access to the members of ISomething
inside your generic class. As ISomething
is only a marker interface without any members, it is of no use to you.
If your classes share common functionality, put this shared functionality into the interface. If they don't, they shouldn't implement the same interface and you should ask yourself about whether your design is right or not.
Please give a more specific example, maybe we can give more practical hints then.
it depends what kind of constrain you wish to add and what kind of operation your class does.
In general you should add a constrain for the type your generic class uses
in the example below the generic class uses the method GetString() which is implemented in the base class. You need to add a constrain on that type to make sure the generic class will find that method
class A
{
public string GetString()
{
return "A";
}
}
class B : A
{
public string GetAnotherString()
{
return "B";
}
}
class GenericClass<T> where T:A
{
private T _obj;
public GenericClass(T obj)
{
_obj = obj;
}
public string GetString()
{
return _obj.GetString();
}
}
public class MyClass
{
public static void Main()
{
GenericClass<A> genericClass=new GenericClass<A>(new B());
Console.WriteLine(genericClass.GetString());
Console.Read();
}
}
精彩评论