首页 > 解决方案 > 创建泛型接口或类以将实例构造函数添加到泛型模型

问题描述

我发现这是最具挑战性的。假设我有以下实体:

public class AccountName : IAccountName, IEntity
    {
        public string firstName { get; private set; }
        public string lastName { get; private set; }
        public string birthDate { get; private set; }
        public string mi { get; private set; }
        public int? chartNumber { get; private set; }

        public AccountName(string lastName, string firstName, DateTime birthDate)
        {
            this.lastName = lastName;
            this.firstName = firstName;
            this.birthDate = birthDate.ToShortDateString();
        }
    }

使用以下接口定义:

public interface IAccountName
    {
        string lastName { get; }
        string firstName { get; }
        string birthDate { get; }     
        string mi { get; }
        int? chartNumber { get; }
    }

让我们进一步说,我有以下“AccountNameModel”,其中包含 AccountName 实体的所有操作:

public class AccountNameModel<T> : IModel
        where T : IAccountName, IEntity
    {
        private readonly T from;
        private readonly T to;

        public AccountNameModel(T from, T to)
        {
            this.from = from;
            this.to = to;
        }

        public async Task ChangeAccountNameAsync()
        {
            var bR = new BillingRepository();
            await bR.ChangeAccountNameAsync(from, to);
        }
    }

现在,我想通过继承的方式向 AccountNameModel 添加一些内容,它创建或强制执行 AccountNameModel 具有以下两个构造函数的概念:

public class AccountNameModel<T>: ISOMETHING??<AccountNameModel<T>>, IModel
{ 
   private readonly T t;

   public AccountNameModel() { }

   public AccountNameModel(T t)
   {
     this.t = t;
   }
}

也就是说,我需要 ISOMETHING 来创建或强制执行 AccountNameModel 具有带有和不带有泛型类 T 的新构造函数这一事实。 简单的接口失败,因为接口中不允许实例构造函数。 那么如何做到这一点呢?(我一直在考虑 T4 模板,但我对 T4 的模板很差)。抽象类可以做到这一点(因为我有很多类似的“模型”)?

非常感谢任何帮助。TIA

标签: c#genericsinterfacet4

解决方案


推荐阅读