确定是否反射型可转换为另一种类型的体现 [英] Determine if a reflected type can be cast to another reflected type

查看:103
本文介绍了确定是否反射型可转换为另一种类型的体现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET(C#),如果您已经通过反思发现两种类型是有可能确定一个可以转换为其他? (隐式和/或显式的)。

我试图做的是建立一个图书馆,使用户可以指定在一个类型的属性映射到另一个类型的属性。一切都很好,如果这两个属性具有匹配的类型,但我希望能够让他们映射特性,其中隐式/显式类型转换是可用的。因此,如果他们有

 类从
{
  公众诠释IntProp {获取;集;}
}

类
{
  众长LongProp {获取;集;}
  公开日期时间DateTimeProp {获取;集;}
}
 

它们将能够说from.IntProp将被分配到to.LongProp(作为含蓄铸存在)。但是,如果他们说,它映射到DateTimeProp我能够确定,有没有可用的演员和抛出异常。

解决方案

 公共静态布尔HasConversionOperator(从类型,类型为)
        {
            FUNC<防爆pression,UnaryEx pression> bodyFunction =体=>防爆pression.Convert(身体,);
            ParameterEx pression INP =前pression.Parameter(从INP);
            尝试
            {
                //如果成功,我们就可以施展'从'类型'到'类型使用隐式强制
                防爆pression.Lambda(bodyFunction(INP),INP).Compile();
                返回true;
            }
            赶上(InvalidOperationException异常)
            {
                返回false;
            }
        }
 

这应该可以解决问题的隐性和显性转换(包括数字类型,类别等。)

In .net (C#), If you have two types discovered through reflection is it possible to determine if one can be cast to the other? (implicit and/or explicit).

What I'm trying to do is create a library that allows users to specify that a property on one type is mapped to a property on another type. Everything is fine if the two properties have matching types, but I'd like to be able to allow them to map properties where an implicit/explicit cast is available. So if they have

class from  
{
  public int IntProp{get;set;}
}

class to
{
  public long LongProp{get;set;}
  public DateTime DateTimeProp{get;set;}
}

they would be able to say that from.IntProp will be assigned to to.LongProp (as an implicity cast exists). But if they said that it mapped to DateTimeProp I'd be able to determine that there's no available cast and throw an exception.

解决方案

public static bool HasConversionOperator( Type from, Type to )
        {
            Func<Expression, UnaryExpression> bodyFunction = body => Expression.Convert( body, to );
            ParameterExpression inp = Expression.Parameter( from, "inp" );
            try
            {
                // If this succeeds then we can cast 'from' type to 'to' type using implicit coercion
                Expression.Lambda( bodyFunction( inp ), inp ).Compile();
                return true;
            }
            catch( InvalidOperationException )
            {
                return false;
            }
        }

This should do the trick for implicit and explicit conversions (including numeric types, classes, etc.)

这篇关于确定是否反射型可转换为另一种类型的体现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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