[英]Modifying value type in generic class implementing generic interface C#
Hei, 喜,
I have been looking but could not find any suitable answer...Maybe point me out. 我一直在寻找,但找不到任何合适的答案...也许要指出我。
So I have an interface and a Point class: 所以我有一个接口和一个Point类:
interface IDoable<T>{
void DoSomething<T>(T ) ;
}
class Point<T>:IDoable <T>{
public T x;
public T y;
public Point(T x, T y){
this.x = x;
this.y = y;
}
public void DoSomething<T>(Point<T> p){
p.x += 10;
p.y += 10;
}
}
But it tells me I cannot do that since int cannot be converted to T. 但是它告诉我我不能这样做,因为int无法转换为T。
I would need the interface to be able to take any type of Point, whether int, float or double or else and modify the value. 我需要接口能够采用任何类型的Point,无论是int,float还是double或其他类型的Point并修改值。 Any ideas?
有任何想法吗?
You are trying to add 10 (an integer) to a value of type T
. 您试图将10(一个整数)添加到
T
类型的值。 T
can be an integer, or a DateTime, or a List, or some other custom class. T
可以是整数,DateTime,List或其他自定义类。 This means that there is absolutely no guarantee that your T
will be able to add itself to an integer. 这意味着绝对不能保证您的
T
能够将其自身添加为整数。
Unfortunately, there is no way in C# to add a generic type constraint that will restrict the parameter to a type that will support a certain operation. 不幸的是,C#中无法添加通用类型约束来将参数限制为支持某种操作的类型。
There are workaround, but they are ugly. 有解决方法,但它们很难看。 ie you could have:
即您可以拥有:
class Point<T>{ ... }
and then have 然后有
class IntPoint : Point<int>, IDoable<int> { ... }
class DoublePoint : Point<double>, IDoable<Double> { ... }
First: 第一:
The definition of your interface is incorrect. 接口的定义不正确。
DoSomething
should not have its own generic parameter. DoSomething
不应具有自己的通用参数。
It should look like this: 它看起来应该像这样:
interface IDoable<T>
{
void DoSomething(T p) ;
}
Second: 第二:
There is no interface, common base class or other possibility in .NET that would allow a generic class to use a certain operator. .NET中没有接口,通用基类或其他可能的方法,允许通用类使用某个运算符。
In other words: You will have to create a class per numeric type you want to use. 换句话说:您将必须为每个要使用的数字类型创建一个类。
If this implementation's DoSomething
method should take a *Point
as parameter - as per your question - the implementation for int
would look like this: 如果此实现的
DoSomething
方法应将*Point
作为参数(根据您的问题),则int
的实现如下所示:
class IntPoint : IDoable<IntPoint>
{
public int x;
public int y;
public Point(int x, int y)
{
this.x = x;
this.y = y;
}
public void DoSomething(IntPoint p)
{
p.x += 10;
p.y += 10;
}
}
You would need to create a class DoublePoint
for doubles
and so on. 您将需要为
doubles
创建类DoublePoint
,依此类推。
You can reduce the amount of repeat code a little bit by creating an abstract base class with an abstract method for the arithmetic operation that would need to be overridden by every derived class. 通过使用用于算术运算的抽象方法创建一个抽象基类,您可以稍微减少重复代码的数量,而每个派生类都需要重写该抽象基类来进行算术运算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.