从通用转换为通用
Cast from generic to generic
简而言之,我正在尝试让这段代码正常工作:
class it<X>
{
X[] data;
int pos;
public Y get<Y>()
{
return (Y) data[pos];
}
}
基本上,我有很多不同基元的数组需要在另一个地方作为不同的基元进行处理。前面的代码无法编译,因为编译器不知道 X 和 Y 是什么。但是,以下内容:
public Y get<Y>()
{
return (Y) (object) data[pos];
}
但是,我得到运行时异常,如:
InvalidCastException: Cannot cast from source type to destination type.
it[System.Double].get[Single]()
这看起来很愚蠢,因为 C# 显然在浮点数和双精度数(以及其他原语)之间进行了强制转换。我猜它与拳击等有关,但我对 C# 很陌生,所以我真的不知道 - 我想我已经习惯了 C++ 模板。请注意,X 和 Y 之间的转换始终存在 - 我可以通过某种方式告诉编译器吗?
您可以使用 Convert
的 ChangeType
方法:
public Y get<Y>()
{
return (Y)Convert.ChangeType(data[pos], typeof(Y));
}
在您的 class 和方法中添加一些 generic constraints 可能也是个好主意,以确保只能传递原语:
class it<X> where X : struct
public Y get<Y>() where Y : struct
简而言之,我正在尝试让这段代码正常工作:
class it<X>
{
X[] data;
int pos;
public Y get<Y>()
{
return (Y) data[pos];
}
}
基本上,我有很多不同基元的数组需要在另一个地方作为不同的基元进行处理。前面的代码无法编译,因为编译器不知道 X 和 Y 是什么。但是,以下内容:
public Y get<Y>()
{
return (Y) (object) data[pos];
}
但是,我得到运行时异常,如:
InvalidCastException: Cannot cast from source type to destination type.
it[System.Double].get[Single]()
这看起来很愚蠢,因为 C# 显然在浮点数和双精度数(以及其他原语)之间进行了强制转换。我猜它与拳击等有关,但我对 C# 很陌生,所以我真的不知道 - 我想我已经习惯了 C++ 模板。请注意,X 和 Y 之间的转换始终存在 - 我可以通过某种方式告诉编译器吗?
您可以使用 Convert
的 ChangeType
方法:
public Y get<Y>()
{
return (Y)Convert.ChangeType(data[pos], typeof(Y));
}
在您的 class 和方法中添加一些 generic constraints 可能也是个好主意,以确保只能传递原语:
class it<X> where X : struct
public Y get<Y>() where Y : struct