动态转换C#

时间:2013-12-28 04:53:27

标签: c# casting

基本上我有

long readval;
unchecked
{
      readval = (long)mycustom.gg; 
     //gg is ulong.MaxValue, mycustom is ulong enum
}
//readval at this point is -1 as expected
Type underlying = Enum.GetUnderlyingType(typeof(mycustom)); 

//underlying is ulong or UInt64
var value = Convert.ChangeType(readvalue, underlying); //Exception cannot convert long value of -1 to ulong, out of range
mycustom returnval = (mycustom)Enum.ToObject(typeof(mycustom), value);

这只是一段测试代码,我只需要弄清楚即使long的值超出范围,如何从long转换为底层类型。在实际的生产代码中,枚举类型mycustom是通用的,readval将始终为long类型。我把mycustom放在这个代码中,以便更容易理解我正在尝试做什么以及我遇到的问题。例外是var value = Convert.ChangeType

2 个答案:

答案 0 :(得分:3)

如何使用表达式树来执行unchecked转换?

long readval;
unchecked
{
    readval = (long)mycustom.gg;
    //gg is ulong.MaxValue, mycustom is ulong enum
}
//readval at this point is -1 as expected
Type underlying = Enum.GetUnderlyingType(typeof(mycustom));

//underlying is ulong or UInt64
var lambda = Expression.Lambda(
                Expression.Convert(
                    Expression.Constant(readval),
                    underlying)).Compile();

var value = Convert.ChangeType(lambda.DynamicInvoke(), underlying);
mycustom returnval = (mycustom)Enum.ToObject(typeof(mycustom), value);

您仍然需要Convert.ChangeType取消装箱lambda.DynamicInvoke()结果,但它有效,因为它会返回underlying类型值。

并且您无法生成类型化的lambda,因为您在编译时不知道underlying类型。

答案 1 :(得分:0)

你是不是只是试图从一个长的枚举变成一个又长又一个又一个?

enum mycustom : ulong  
{
    gg = ulong.MaxValue
};


protected void ButtonServer_Click(object sender, EventArgs e)
{
    long readval;

    unchecked
    {
        readval = (long)mycustom.gg;
        //gg is ulong.MaxValue, mycustom is ulong enum
    }

    mycustom returnval = (mycustom) readval;
}