[英]How can I access values in another class inherited from public class C#?
I get an error when inheriting from public class I can't access values of another class.从公共 class 继承时出现错误我无法访问另一个 class 的值。
AppEngine.cs AppEngine.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestEngine
{
public class AppEngine : Appstrings
{
public async Task<string> Testing()
{
return wrongUserName;
}
}
}
Appstrings.cs应用字符串.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace TestEngine
{
public class Appstrings
{
string wrongUserName = "Wrong username. Please check and try again..";
}
}
I want to access the values that I defined in the Appstrings class by inheriting them from the AppEngine class.我想通过从 AppEngine class 继承来访问我在 Appstrings class 中定义的值。 This is the code I wrote, but the error I get is 'Appstrings.wrongUserName' is inaccessible due to its protection level.
这是我编写的代码,但我得到的错误是'Appstrings.wrongUserName' is inaccessible due to its protection level.
It is said that it cannot be inherited due to protection, but the class construction is public.据说因为保护不能继承,但是class结构是公开的。 Where do you think I am doing wrong?你觉得我哪里做错了?
Base on C# language reference基于C# 语言参考
Class members can have any of the five kinds of declared accessibility and default to private declared accessibility. Class 成员可以具有五种声明的可访问性中的任何一种,并且默认为私有声明的可访问性。
So, the wrongUserName
has the private
accessibility inside the Appstrings
class.因此, wrongUserName
在Appstrings
class 中具有private
可访问性。 You must specify the accessibility of the member explicitly to internal
, protected
, or public
(not recommended).您必须明确指定成员对internal
、 protected
或public
的可访问性(不推荐)。
namespace TestEngine
{
public class Appstrings
{
protected string wrongUserName = "Wrong username. Please check and try again..";
}
}
Access modifiers also apply to properties.访问修饰符也适用于属性。 If you don't set one it's implicitely set to private
.如果你不设置一个,它会被隐式设置为private
。 So if you want to set it to public
you'll need to add it infront of the property, although protected
would also work if you only want to make it accessable by inheritance:因此,如果您想将其设置为public
,则需要将其添加到属性的前面,尽管如果您只想使其可由 inheritance 访问, protected
也可以:
public string wrongUsername = "...";
See Microsoft docs for the complete list of access modifiers.有关访问修饰符的完整列表,请参阅Microsoft 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.