采取方案

BaseA-> SubB-> SubSubC

说明:SubSubC类继承了SubB类。 SubB类继承了BaseA类

BaseA-> SubD-> SubSubE

说明:SubSubE类继承了SubD类。 SubB类继承了BaseA类

不久..

因此,有许多类的父类都作为BaseA。 BaseA类具有所有方法共有的一些属性。例如:CustomerID,LastLogin,UniqueName等。

这就是我正在使用的服务中设计类的方式。

我的疑问是,在调用服务方法时,所有方法都将期望任何SubSub类的参数。谁能告诉我,是否可以在一个地方为BaseA的属性分配值,这样在创建SubSub对象时我不需要每次都填充基本属性?

我正在使用C#作为我的语言。

码:

public class BaseA
    {
        public int CustomerId { get; set; }
        public string UniqueName { get; set; }
    }

    public class SubB : BaseA
    {
    }
    public class SubSubC : SubB
    {

    }

    public class SubD : BaseA
    {
    }
    public class SubSubE : SubD
    {

    }

    public class MyMain
    {
        public void SendRequestToService1()
        {
            (new MyServiceObject()).ServiceMethod1(new SubSubC());
        }

        public void SendRequestToService2()
        {
            (new MyServiceObject()).ServiceMethod2(new SubSubE());
        }
    }


在上面的代码中,在SendRequestToService1和SendRequestToService2中,我需要初始化基类属性CustomerId和UniqueName。
例如:

(new SubSubC(){ CustomerId=2, UniqueName="XXBB" });


如果有很多方法,我需要为各自的类每次都初始化这些属性。有没有一种方法可以在一处初始化基本属性CustomerId和UniqueName,以使继承的类(此处为SubSubC,SubSubE)在创建对象时无需初始化?

最佳答案

您是否正在寻找以下功能?

    //dummy class replacing the service object and it's methods
    public class MyServiceObject
    {
        public void ServiceMethod1(SubSubC param)
        { }
        public void ServiceMethod2(SubSubE param)
        { }
    }

    public class BaseA
    {
        public int CustomerId { get; set; }
        public string UniqueName { get; set; }
    }

    public class SubB : BaseA
    {
    }
    public class SubSubC : SubB
    {
    }

    public class SubD : BaseA
    {
    }
    public class SubSubE : SubD
    {
    }

    public class MyMain
    {
        //declare the SubSub objects
        //SubSubC subSubC;
        //SubSubE subSubE;
        BaseA baseA;

        public MyMain()
        {
            //assign the values to each class in the MyMain contrsuctor
            baseA = new BaseA { CustomerId = 2, UniqueName = "XXBB" };

        }

        public void SendRequestToService1()
        {
            var subSub=new SubSubC();
            (new MyServiceObject()).ServiceMethod1(Initialize(subSub));
        }

        public void SendRequestToService2()
        {
            var subSub = new SubSubE();
            (new MyServiceObject()).ServiceMethod2(Initialize(subSub));
        }

        private T Initialize<T>(T subSub) where T:BaseA
        {
            subSub.CustomerId = baseA.CustomerId;
            subSub.UniqueName = baseA.UniqueName;
            return subSub;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            MyMain myMain = new MyMain();
            myMain.SendRequestToService1();
            myMain.SendRequestToService2();
        }
    }

09-28 08:57