有时候,我真不明白那些T
C#的泛型的权利。我有一个通用的结构初始化非通用对象与通用对象
public struct ValueWithUnit<T>
{
public ValueWithUnit(T _value, Unit _unit)
{
Unit = _unit;
Value = _value;
}
public Unit Unit { get; }
public T Value { get; }
}
(Unit
是enum
,T
应该是数字,但没有可用于该目的的约束)。
对于WCF我需要一个非通用版本的,T
是double
。于是我想到了:
public struct DoubleValueWithUnit
{
public DoubleValueWithUnit(double _value, Unit _unit)
{
Unit = _unit;
Value = _value;
}
public DoubleValueWithUnit(ValueWithUnit<T> _valueWithUnit)
{
Unit = _valueWithUnit.Unit;
Value = Convert.ToDouble(_valueWithUnit.Value);
}
public Unit Unit { get; set; }
public double Value { get; set; }
}
但第二个构造不会编译: error CS0246: The type or namespace name 'T' could not be found ...
和Convert.ToDouble与 Cannot resolve method 'ToDouble(T)' Candidates are...
抱怨我知道我可以添加一个转换方法泛型类:
public DoubleValueWithUnit ToDoubleValueWithUnit()
{
return new DoubleValueWithUnit(Convert.ToDouble(Value), Unit);
}
工程。但有没有可能添加一个具有泛型参数的构造函数到非泛型类/结构?
你为什么不只是使用'ValueWithUnit'而不是DoubleValueWithUnit'的'? –
Maarten
你试图做什么[是不可能的(https://开头计算器。com/questions/700966/generic-type-in-constructor) - 但是,Maarten的建议可能是这里最好的解决方案 – Rob
@Maarten,因为WCF与泛型兼容...... –