我有以下代码:
public interface IDrilldown
{
void AddCriteria<T>(T Criterion);
}
public class MyClass<W> : IDrilldown // where W : class
{
void IDrilldown.AddCriteria<T>(T Criterion)
{
W value = Criterion as W;
...
}
}
不幸的是,除非 W 在代码中包含约束,否则我上面的转换将不起作用。我想使用值类型来实现它。有可能吗?
我不能让 W 和 T 成为同一类型。我的接口(interface)没有全局关联的类型,只有内部数据类型。
这样我就可以拥有一个所有具有不同 T 的列表
最佳答案
我找到了一种方法来做到这一点,虽然有点笨拙,但可以正常工作:
class MyClass<W> : IDrilldown {
void IDrilldown.AddCriteria<T>(T Criterion) {
if (Criterion is W) {
W value = (W)Convert.ChangeType(Criterion, typeof(W));
// value is W, have fun
// or - as Snowbear pointed out in the comments
W value = (W)(object)Criterion;
// works just as well....
} else {
// value is NOT W and could not be converted.
}
}
}
唯一的缺点是,Convert.ChangeType
将使用转换器在内部对象之间进行更改,因此 string value = (string)Convert.ChangeType(1, typeof(string))
将工作并返回 "1"
而不是抛出异常。
为了阐明其工作原理,文档指出:
For the conversion to succeed, value must implement the IConvertible interface, because the method simply wraps a call to an appropriate IConvertible method. The method requires that conversion of value to conversionType be supported.
因此,要使此方法与自定义类型一起使用,您需要实现 IConvertible
接口(interface)以将一种自定义类型转换为任何其他类型。在上面的代码示例中,如果两者 T
和W
是同一类型,则Convert.ChangeType
将成功,即使自定义对象没有实现 IConvertiable
。
关于c# - 在没有类约束的情况下将一个泛型转换为另一个泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332655/