【问题标题】:Expression to convert a Guid to a string将 Guid 转换为字符串的表达式
【发布时间】:2012-10-22 21:28:36
【问题描述】:

我需要将一个对象的所有公共属性复制到另一个类型的另一个对象。 Jon Skeet 创建的库MiscUtil 包含PropertyCopy 类,它非常适合我需要的东西,除了一件事。我在源对象中有一个属性需要转换为目标对象中的另一种类型(Guid => 字符串)。

来自 PropertyCopy 的部分代码:

if (!targetProperty.PropertyType.IsAssignableFrom(sourceProperty.PropertyType))
{
    //My specific case
    if (sourceProperty.PropertyType == typeof(Guid) && targetProperty.PropertyType == typeof(string))
    {
        //Expression.Bind(targetProperty, [--Convert Guid to string expression??--]);
    }
    else
    {
        throw new ArgumentException("...");
    }                              
}

那么是否可以创建一个表达式来将源属性的转换绑定到目标?

【问题讨论】:

    标签: c# mapping expression


    【解决方案1】:

    我认为

    Expression.Bind(targetProperty, (Expression<Func<Guid,string>>) (v=>v.ToString()));
    

    会起作用的...

    【讨论】:

      【解决方案2】:

      下面的代码在将 Guid 绑定到目标属性之前将其转换为字符串:

      if (sourceProperty.PropertyType == typeof(Guid) && targetProperty.PropertyType == typeof(string))
      {
          Expression callExpr = Expression.Call(Expression.Property(sourceParameter, sourceProperty), typeof(Guid).GetMethod("ToString", new Type[] { }));
          bindings.Add(Expression.Bind(targetProperty, callExpr));
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-12
        • 2012-09-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-05
        相关资源
        最近更新 更多