使用扩展方法分配 属性 的好方法
Good way to assign property with extension method
我处于可以使用 AutoMapper 的情况。但是 属性 我的对象上的名称不同并且 AutoMapper 映射将为这只是一个奇怪的用法付出额外的努力。
这是我的代码现在的样子
ObjectOne.PropOne = ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)
扩展方法如下所示 -
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;
}
有没有一种方法可以避免分配并可以像下面那样做?
ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)
您可以使用:
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);
}
但请注意,ref 扩展方法仅适用于 C# 7.2+
我处于可以使用 AutoMapper 的情况。但是 属性 我的对象上的名称不同并且 AutoMapper 映射将为这只是一个奇怪的用法付出额外的努力。
这是我的代码现在的样子
ObjectOne.PropOne = ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)
扩展方法如下所示 -
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;
}
有没有一种方法可以避免分配并可以像下面那样做?
ObjectOne.PropOne.CopyFrom(ObjectTwo.PropX)
您可以使用:
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);
}
但请注意,ref 扩展方法仅适用于 C# 7.2+