【问题标题】:Unable to access class variable C#无法访问类变量 C#
【发布时间】:2018-10-17 03:01:21
【问题描述】:

当我尝试访问类中的服务类变量时,它会显示一些错误。但是,当我尝试在方法中访问相同的 Class 变量时,它工作正常。

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
}
}

【问题讨论】:

  • 我没有时间阅读任何文档 - 所以我们必须花时间为您阅读文档?
  • 你不能在方法之外设置任何属性。
  • 我猜你想使用构造函数!顺便说一句,方法有什么问题?
  • 使用; 我得到在类、结构或接口成员声明中出现意外符号“=”。没有它,我会得到 Unexpected symbol 'variable'.
  • 您需要;。对于Unexpected symbol 'variable'.,请参阅上面的@apomene 评论。你不能在这样的函数之外编写代码。编译器不会让你。考虑下面@Oilid 的解决方案。

标签: c# wcf methods


【解决方案1】:

试试这个:

ServiceName.ServiceClass variable = new ServiceName.ServiceClass {member = 10};

【讨论】:

  • 如上所述,您不能在方法之外设置任何属性。
【解决方案2】:

@apomene 是对的,您不能在方法之外设置任何属性。如果您需要提供一个常量默认值,请在属性行的末尾添加=10;

或者,如果你需要在一个方法中做,你可以使用constructor.类似的东西;

public Sample()
{
    member = 10;
}

【讨论】:

    猜你喜欢
    • 2017-10-07
    • 2014-06-04
    • 1970-01-01
    • 1970-01-01
    • 2014-08-22
    • 2022-11-18
    • 2015-12-07
    • 1970-01-01
    • 2023-03-27
    相关资源
    最近更新 更多