如何检查是否隐含或明确的转换存在? [英] How to check if implicit or explicit cast exists?

查看:124
本文介绍了如何检查是否隐含或明确的转换存在?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个泛型类,我想强制类型参数的情况下,始终为铸能够/转换的字符串。是否有可能为此而不例如使用一个接口?

I have a generic class and I want to enforce that instances of the type parameter are always "cast-able" / convertible from String. Is it possible to do this without for example using an interface?

可能的实现:

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

理想的实现:

Ideal implementation:

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();
        }
        // ...
    }
}

我为什么会preFER这个理想的执行情况的原因,主要是为了不给力所有的TS实施IConvertibleFrom&LT;>

The reason why I would prefer this "ideal" implementation is mainly in order not to force all the Ts to implement IConvertibleFrom<>.

推荐答案

既然你想从密封字符串类型转换,你可以忽略可能为空,拳击,参考和显式转换。只有 op_Implicit()资格。一个更通用的方法是由System.Linq.Ex pressions.Ex pression类提供的:

Given that you want to convert from the sealed String type, you can ignore possible nullable, boxing, reference and explicit conversions. Only op_Implicit() qualifies. A more generic approach is provided by the System.Linq.Expressions.Expression class:

using System.Linq.Expressions;
...
    public static T DoSomethingWith(string s)
    {
      var expr = Expression.Constant(s);
      var convert = Expression.Convert(expr, typeof(T));
      return (T)convert.Method.Invoke(null, new object[] { s });
    }

谨防反思的成本。

Beware the cost of Reflection.

这篇关于如何检查是否隐含或明确的转换存在?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆