C# “C”;由于其保护级别而无法访问”;构造函数中的错误
子类“caesar”的构造函数给出了一个错误。它表示名称、类型由于其保护级别而不可访问。怎么会?因为这是从“Cipher”类派生的子类,所以不应该给出这样的错误。我怎样才能克服这种情况。但我希望这些变量是私有的。我不想把它们改成公共的 ***第二个代码示例有效。有人能看出区别吗C# “C”;由于其保护级别而无法访问”;构造函数中的错误,c#,inheritance,encapsulation,access-modifiers,C#,Inheritance,Encapsulation,Access Modifiers,子类“caesar”的构造函数给出了一个错误。它表示名称、类型由于其保护级别而不可访问。怎么会?因为这是从“Cipher”类派生的子类,所以不应该给出这样的错误。我怎样才能克服这种情况。但我希望这些变量是私有的。我不想把它们改成公共的 ***第二个代码示例有效。有人能看出区别吗 namespace Encrypter { class Cipher { public Cipher(string name, string type) {
namespace Encrypter
{
class Cipher
{
public Cipher(string name, string type)
{
setName(name);
setType(type);
}
private string name;
private string type;
public void setName(string newName)
{
name = newName;
}
public string getName()
{
return name;
}
public void setType(string newType)
{
type = newType;
}
public string getType()
{
return type;
}
public string encrypt(string text)
{
return text;
}
public string decrypt(string text)
{
return text;
}
}
}
namespace Encrypter
{
class Caesar : Cipher
{
private int shiftamount;
private string shiftdirection;
public Caesar(int shiftamount, string shiftdirection) : base(name, type)
{
setShiftamount(shiftamount);
setShiftdirection(shiftdirection);
}
public void setShiftamount(int newShiftamount)
{
shiftamount = newShiftamount;
}
public int getShiftamount()
{
return shiftamount;
}
public void setShiftdirection(string newShiftdirection)
{
shiftdirection = newShiftdirection;
}
public string getShiftdirection()
{
return shiftdirection;
}
}
}
-----------------------------新编辑----------------
无法从派生类访问私有成员。受保护和公众可以。你必须保护他们。这样,只有类及其“子类”可以访问 访问权摘要:
只能从该类方法访问,其他方法不能访问private:
可以从该类及其子类的方法访问受保护:
只能从同一程序集中的方法访问内部:
与来自其他程序集的派生类的内部+方法相同受保护的内部:
每个人都可以访问public:
private
意味着只有声明类可以访问成员(这意味着继承的类型也不能)
protected
意味着声明类和任何子类都可以访问成员,但这些成员之外的类型不能访问
另一方面,getter和setter函数通常不在.NET语言中使用。属性封装了此功能,应该使用这些属性。比如,
private string name;
public string Name
{
get { return name; }
set { name = value; }
}
看起来您在定义派生类构造函数时犯了一个错误。如果要将
name
和type
值传递给超类,则必须将它们作为额外的构造函数参数传入(派生类构造函数中总共有4个参数)。例如,将其更改为此应该可以:
public Caesar(int shiftamount,
string shiftdirection,
string name,
string type)
: base(name, type)
你还可以采取其他一些策略
public Caesar(int shiftamount, string shiftdirection)
: base(name, type)
{
问题在于private
字段的名称和类型-子类无法访问它们,除非它们被标记为protected
。我怀疑你真正想要的是
public Caesar(int shiftamount, string shiftdirection)
: base("Caesar5", "Caesar")
{
啊!您使用的是C#…使用属性而不是getter/setter方法。对于海报来说,这可能也是一个很好的读物。代码看起来非常像Java。;-)是的,实际上我最喜欢的语言是Java,所以我非常习惯它。由于C#与Java相似,我也在C#D中使用我的Java编程习惯,但是的,无论如何你是对的:)哦,你是对的。我刚刚对我的帖子进行了编辑。正如你所说的。非常感谢。
public Caesar(int shiftamount, string shiftdirection)
: base("Caesar5", "Caesar")
{