c# - 如何在 C# 中将 const 参数传递给抽象类父类?

标签 c# .net class parameters abstract

我编写了以下多态代码:

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

最佳答案

您需要向 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 的构造函数也不能是私有(private)的。

关于c# - 如何在 C# 中将 const 参数传递给抽象类父类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4380411/

相关文章:

c# - LINQ 和唯一 ID

java - IntelliJ - 如何在整个项目中仅运行一个(主)类

c# - 使用 .NET 库 ECDsaCng 验证 BouncyCaSTLe ECDsa 签名

c# - 如何使用 C# 从字符串中单独检查/过滤大写单词?

c# - 可选参数 "must be a compile-time constant"

c++ - 客户端的堆排序 vector ,错误地传递迭代器?

c++ - C++ 中的运算符重载和符号

c# - OmniSharp 服务器在打开 Unity 项目时抛出 System.IO.FileNotFoundException : Could not load file or assembly 'netstandard,

c# - SQL 选择具有多个整数值的行

.net - 如何基于多态性干净地处理不同的行为