C# C语言中的属性访问限制#
试图找出背后的原因 情景1 情景2C# C语言中的属性访问限制#,c#,asp.net,oop,inheritance,C#,Asp.net,Oop,Inheritance,试图找出背后的原因 情景1 情景2 有人能告诉我这背后的原因吗???很简单。不能在类上下文中进行变量赋值(无声明)。您需要使用构造函数将赋值放入: public class DerivedCustomer : BaseCustomer { public DerivedCustomer() { _name = "hello"; } ... } 。。。或者把它放在声明中: public class BaseCustomer { protected s
有人能告诉我这背后的原因吗???很简单。不能在类上下文中进行变量赋值(无声明)。您需要使用构造函数将赋值放入:
public class DerivedCustomer : BaseCustomer
{
public DerivedCustomer()
{
_name = "hello";
}
...
}
。。。或者把它放在声明中:
public class BaseCustomer
{
protected string _name = "hello";
}
注:专家可能会发现我的简化解释有例外。为了解释OP的主要意图,我保持简单
在某种程度上,类实际上只包含声明。这可以是一个字段:
public class Customer
{
private string _name;
}
或财产:
//Example 1 - Simple property
public class Customer
{
public string Name { get; set; }
}
//Example 2 - Publically gettable (but not settable) property with private field (which is settable)
public class Customer
{
private string _name; //this is a field
public string Name => _name; //this is a property that relies on the field
}
或一种方法:
public class Customer
{
public string GetName()
{
return "John";
}
}
概括起来,我将总结如下:
类仅包含有关其结构的声明:字段、属性和方法
类不直接包含代码(即使用字段/属性的逻辑)
但是,类“方法”或“属性”可以包含代码(即使用字段/属性的逻辑),但该代码被视为方法/属性的一部分,而不是类的一部分(直接)
你想做的事对我来说没什么意义。我不太确定通过尝试访问这些位置的
\u name
您希望实现什么
只有在可以引用该字段的位置引用该字段才有意义:
- 在方法体中-如果在方法执行期间需要该字段
- 在属性中-在设置/获取属性期间使用字段时
- 在构造函数中设置字段的值
- 你想用
做什么\u name
- 假设您可以引用您想要引用的字段;您希望何时执行此代码
- 这与简单地使用方法(或构造函数)有什么不同
\u name=“Foo”代码>?如果是这样的话,那就更清楚地把它编辑成问题了。实际上,您有一个没有终止符的裸变量代码>在任何上下文中都不是有效的代码。您如何推断它是“无法访问”的结论?所显示的代码片段根本不是有效的C#语法。@Fildor:每当我听到几乎任何开发人员将某个东西称为“不可访问”,它的意思是“我在智能感知中找不到它”。@Flater是的-舒适IDE的缺点…我的问题是,这背后的原因是什么???@Kgn web没有意义。什么时候应该执行这样的代码?
//Example 1 - Simple property
public class Customer
{
public string Name { get; set; }
}
//Example 2 - Publically gettable (but not settable) property with private field (which is settable)
public class Customer
{
private string _name; //this is a field
public string Name => _name; //this is a property that relies on the field
}
public class Customer
{
public string GetName()
{
return "John";
}
}