如何在派生类中获取抽象类构造函数值

时间:2016-06-15 09:59:46

标签: c# class abstract-class

如何在派生类中获取抽象类构造函数值。

   public abstract class ABC
        {
            private string data = "hi";

            protected ABC(string myString)
            {
                myString = data;
            }
        }
        public class XYZ: ABC
        {
            public string abc= "";
            public XYZ(string myString)
                : base(myString)
            {
                abc = myString;
            }
        }

          XYZ var = new XYZ("567");
          Response.Write(var.abc);

我的输出为567,如何获得“hi567”或“567hi”甚至“hi”。

2 个答案:

答案 0 :(得分:1)

非常简单 - 但有点奇怪:

using System;

namespace ConsoleApplication1
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var var = new XYZ("567");
            Console.WriteLine(var.abc);

            Console.ReadLine();
        }
    }

    public abstract class ABC
    {
        private string data = "hi";

        protected ABC(string myString, out string outString)
        {
            myString = this.data;
            outString = myString;
        }
    }

    public class XYZ : ABC
    {
        public string abc = "";

        public XYZ(string myString) : this(myString, string.Empty)
        {
        }

        private XYZ(string myString, string outString) : base(myString, out outString)
        {
            this.abc = outString + myString;
        }
    }
}

您只需要将out参数传递给基础构造函数。

答案 1 :(得分:0)

这可以提供您想要的输出,但不确定您的想法 -

    public abstract class ABC
    {
        private string data = "hi ";

        protected ABC(string myString)
        {
            data += myString;
        }

        public string PropToReturnValuePassedInCtor{ get { return data; } }
    }

    public class XYZ: ABC
    {
        public string abc = "";

        public XYZ(string myString)
            : base(myString)
        {
            abc = base.PropToReturnValuePassedInCtor;
        }
    }

    var t = new XYZ("567");
    Console.Write(t.abc); //hi 567