【问题标题】:How to pass const arguments to an abstract class parent in C#?如何将 const 参数传递给 C# 中的抽象类父级?
【发布时间】:2011-05-21 19:01:44
【问题描述】:

我编写了以下多态代码:

public abstract class  A  
{  
    readonly int x;  
    A(int i_MyInt)  
    {  
        x = i_MyInt;  
    }  
}  

public abstract class B : A  
{  
    //holds few integers and some methods      
}  


// concrete  object class  
public class C : B   
{  
   // holds some variables and mathods  
    C(int MyInt)  
    {   
      // here i would like to initialize A's x  
    }  
}  

如何从 C 初始化 A 的 x 我尝试将参数传递给 A 的 C'tor - 但没有奏效..

请帮忙, 提前致谢 阿米托斯80

【问题讨论】:

    标签: c# .net class parameters abstract


    【解决方案1】:

    您需要向 B 添加一个构造函数,该构造函数接受一个整数并将其传递给 A 的构造函数。然后,您可以从 C 调用此构造函数。

    public abstract class B : A
    {  
        public B(int myInt) : base(myInt)
        {
            // other initialization here...
        }  
    }  
    
    public class C : B
    {
        // holds some variables and mathods  
        public C(int myInt) : base(myInt)
        {
            // other initialization here...
        }
    }  
    

    A 的构造函数也不能是私有的。

    【讨论】:

    • +1 无论如何你都需要这个,因为 A 类没有默认构造函数。
    • 另外,您也可以将 A 的 x 设为 protected 或 public,然后从 C 的构造函数中设置它。
    • 非常感谢 Mark,这很有帮助。
    猜你喜欢
    • 2021-05-08
    • 2020-09-11
    • 2021-11-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 2012-02-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多