【问题标题】:C#: Avoid duplicate code in Extension method When the base class is extendedC#:在扩展基类时避免在扩展方法中重复代码
【发布时间】:2022-06-10 22:07:16
【问题描述】:

我有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
{
    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;}
}

【问题讨论】:

  • 在您的代码中,B 类不继承 A 类

标签: c#


猜你喜欢
  • 2017-09-25
  • 1970-01-01
  • 1970-01-01
  • 2011-05-12
  • 1970-01-01
  • 2011-09-25
  • 2023-03-07
  • 1970-01-01
  • 2011-06-04
相关资源
最近更新 更多