简体   繁体   English

用扩展方法分配属性的好方法

[英]Good way to assign property with extension method

I'm in a situation where I could use AutoMapper. 我处于可以使用AutoMapper的情况。 But property names on my objects are different and AutoMapper mapping will additional effort for this just one odd usage. 但是我对象上的属性名称不同,AutoMapper映射将为这种奇怪的用法付出更多的努力。

here is my code looks like now 这是我的代码看起来像现在

ObjectOne.PropOne = ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)

Extension method looks like below - 扩展方法如下所示-

public static T CopyFrom<T, U>(this T target, U source)
{
    bool isValidString = (source is string && source != null && !string.IsNullOrEmpty(source.ToString()));
    bool isValidNonString = (!(source is string) && source != null);

    if (isValidString || isValidNonString)
        target = Utils.GetValue<T>(source);

    return target;
}

is there a way where I can avoid the assignment and can do like below? 有没有一种方法可以避免分配并且可以像下面那样进行操作?

ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)

You may use: 您可以使用:

public static void CopyFrom<T, U>(ref this T target, U source)
{
     bool isValidString = (source is string && source != null && !string.IsNullOrEmpty(source.ToString()));
     bool isValidNonString = (!(source is string) && source != null);

     if (isValidString || isValidNonString)
         target = Utils.GetValue<T>(source);
}

but please note that ref Extension methods are only available in C# 7.2+ 但请注意,ref扩展方法仅在C#7.2+中可用

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM