从局部类访问类字段 [英] Access class fields from partial class
问题描述
我目前处于必须使用局部类的场景中.在这个局部类中,我有一些方法需要解决另一个类中的字段.
I'm currently in a scenario in which I have to make use of partial classes. In this partial class I have a few methods that need to address fields in the other class.
例如
很抱歉:第一类已经声明为 partial
!
I'm sorry: the first class is already declared partial
!
public partial class myClass
{
private string _myString;
public string myString
{
get { return _myString; }
set { _myString = value; }
}
}
和
public partial class myClass
{
public void doSomething()
{
myString = "newString";
}
}
编译器说 myString
在部分类中不存在!
The compiler says myString
doesn't exist in the partial class!
我该如何克服这个问题?
How can I overcome this problem?
推荐答案
您需要用发布的代码来解决一些问题:
There are a few things you need to fix with the code you posted:
在C#中使用局部类时,该类的所有所有部分都必须声明为局部类
When using partial classes in C# all parts of the class must be declared as partial classes
你有
public class myClass {}
public partial class myClass {}
需要成为谁
public partial class myClass {}
public partial class myClass {}
第二,您正在尝试设置
myString="newString";
但是 myString
是不带setter的公共属性.
but myString
is a public property without a setter.
因此,您可以在声明 myString
public string myString
{
get{ return _myString; }
set { _myString = value; }
}
或仅使用
_myString="newString";
在第二个类文件中.
这篇关于从局部类访问类字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!