小编Joa*_*iro的帖子

如何检查隐式或显式转换是否存在?

我有一个泛型类,我想强制类型参数的实例始终从String"cast-able"/ convertible.没有例如使用接口可以做到这一点吗?

可能的实施:

public class MyClass<T> where T : IConvertibleFrom<string>, new()
{
    public T DoSomethingWith(string s)
    {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

理想的实施:

public class MyClass<T>
{
    public T DoSomethingWith(string s)
    {
        // CanBeConvertedFrom would return true if explicit or implicit cast exists
        if(!typeof(T).CanBeConvertedFrom(typeof(String))
        {
            throw new Exception();
        }
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

我更喜欢这种"理想"实现的原因主要是为了不强迫所有Ts实现IConvertibleFrom <>.

.net c# casting

5
推荐指数
1
解决办法
2767
查看次数

标签 统计

.net ×1

c# ×1

casting ×1