无法访问类变量C#
当我试图访问类内的服务类变量时,它显示了一些错误。但是,当我尝试在方法中访问同一个类变量时,它工作得很好无法访问类变量C#,c#,wcf,methods,C#,Wcf,Methods,当我试图访问类内的服务类变量时,它显示了一些错误。但是,当我尝试在方法中访问同一个类变量时,它工作得很好 Eg: public class Sample { ServiceName.ServiceClass variable = new ServiceName.ServiceClass(); variable.member = 10; //This shows error variable not defined } public class Sample { public void met
Eg:
public class Sample
{
ServiceName.ServiceClass variable = new ServiceName.ServiceClass();
variable.member = 10; //This shows error variable not defined
}
public class Sample
{
public void methodName()
{
ServiceName.ServiceClass variable = new ServiceName.ServiceClass();
variable.member = 10; //This works fine and allows value allocation
}
}
试试这个:
ServiceName.ServiceClass variable = new ServiceName.ServiceClass {member = 10};
@apomene是对的,您不能在方法之外设置任何属性。如果需要提供一个恒定的默认值,请添加
=10属性行末尾的代码>
或者,如果你需要用一种方法来做,你可以使用
public Sample()
{
member = 10;
}
我没有时间阅读任何文档-因此我们必须花时间为您阅读文档?您不能在方法之外设置任何属性。我猜您想使用构造函数!顺便说一句,方法有什么问题?使用代码>我在类、结构或接口成员声明中获得意外的符号“=”。如果没有它,我会得到意外的符号“variable”。您需要代码>。有关意外符号“变量”。
请参阅上面@apomene的评论。你不能在那样的函数之外编写代码。编译器不允许你这样做。考虑下面的“CulID”解决方案,如上所述,不能在方法之外设置任何属性。