c#:在扩展基类时避免在扩展方法中重复代码

  • 本文关键字:扩展 方法 代码 基类 c#
  • 更新时间 :
  • 英文 :


我有类A和类B继承类A。

类A有扩展方法。我的问题是类A扩展方法没有所有的属性,所以,我需要为类b创建扩展方法。

在这种情况下,如何使用A类扩展方法而避免B类扩展方法中的重复代码?

public class A
{
public int Id { get; set; }
public string FirstName {get; set; }
public string LastName { get; set; }
}
public class B: A
{
public int Age { get; set; }
}
internal static class ClassAExtension
{
public static ADto ExtensionA(this A a)
{
return a != null
? new ADto
{
Id = a.Id,
Name = a.FirstName + " " + a.LastName
}
: null;
}
}
public class ADto
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set;}
}

使用模式匹配。

public static ADto ExtensionA(this A a)
{
if (a is null) return null;
var result = new ADto {
Id = a.Id,
Name = $"{a.FirstName} {a.LastName}"
};
if (a is B b) {
result.Age = b.Age;
}
return result;
}

最新更新