c# - 泛型显式转换

标签 c# generics casting

我实现了从字符串到名为 Foo 的对象的显式转换。

So => Foo f = (Foo)"foo 数据";有效

我需要实现一个将字符串转换为泛型 T 的函数,在这种情况下,T 是 Foo 数据类型。

public T Get<T>(object o){
      // this always return false
      if (typeof(T).IsAssignableFrom(typeof(String)))
      {
            // when i by pass the if above this throws invalid cast exception
            return (T)(object)str;
      }
      return null; 
}

// When I call this, it generated an error
// Invalid cast from 'System.String' to Foo
Foo myObj = Get<Foo>("another foo object"); 

// when I use the dynamic keyword it works but this is C# 4.0+ feature, my function is in the older framework
return (T)(dynamic)str;

最佳答案

一个使用反射的例子:

class Program
{
    static void Main(string[] args)
    {           
        Foo myObj = TypeResolver.Get<Foo>("Foo data");            
    }
}

class TypeResolver
{
    public static T Get<T>(object obj)
    {
        if (typeof(T).CanExplicitlyCastFrom<string>())
        {                             
            return obj.CastTo<T>();
        }
        return default(T);
    }
}

public static class Extensions
{
    public static bool CanExplicitlyCastFrom<T>(this Type type)
    {
        if (type == null)
            throw new ArgumentNullException("type");

        var paramType = typeof(T);
        var castOperator = type.GetMethod("op_Explicit", 
                                        new[] { paramType });
        if (castOperator == null)
            return false;

        var parametres = castOperator.GetParameters();
        var paramtype = parametres[0];
        if (paramtype.ParameterType == typeof(T))
            return true;
        else
            return false;
    }

    public static T CastTo<T>(this object obj)
    {            
        var castOperator = typeof(T).GetMethod("op_Explicit", 
                                        new[] { typeof(string) });
        if (castOperator == null)
            throw new InvalidCastException("Can't cast to " + typeof(T).Name);
        return (T)castOperator.Invoke(null, new[] { obj });
    }
}

关于c# - 泛型显式转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16114226/

相关文章:

c# - Azure VM 上 FtpWebRequest 处于事件模式 (UsePassive = False) 时为 "500 Syntax error, command unrecognized"

c# - 没有指定 authenticationScheme,也没有找到 DefaultChallengeScheme Cookies Authentication

java - 在异常的参数中使用泛型

java - 对动态代理的调用应该转到动态类型的方法还是静态类型的方法?

generics - 是否可以在具有通用参数和返回类型的结构中使用闭包?

c# - 在派生的 RazorPage 中获取 View Component 的渲染结果

c# - 整数列表中的查找模式

c++ - 从函数双端队列上的迭代器获取函数指针

python - 为什么 astype timedelta64 不能在 ndarray 上工作?

typescript - typescript 转换错误以获取输入值