c# - 在没有类约束的情况下将一个泛型转换为另一个泛型

标签 c# .net generics constraints

我有以下代码:

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)以将一种自定义类型转换为任何其他类型。在上面的代码示例中,如果两者 TW 是同一类型,则Convert.ChangeType 将成功,即使自定义对象没有实现 IConvertiable

关于c# - 在没有类约束的情况下将一个泛型转换为另一个泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6332655/

相关文章:

C# "Enum"序列化 - 反序列化为静态实例

c# - Xamarin.Forms:导航到页面失败

c# - 更改了 .NET 4.5 中 string.Empty(或 System.String::Empty)的行为

c# - 与 WCF 通信的 Android 应用程序

c# - WinForms 调用/BeginInvoke

c# - 为什么 DataReader 给出 "Enumeration Yielded No Results"?

.NET HTTP 处理程序——如何发送自定义响应?

C++ 模板 : Create a specialized function for a specific data type

database - 从数据库获取数据并填充数组的Golang抽象函数

generics - F# 中下划线泛型的作用是什么