c# - 在一个继承类的部分类中声明类字段,然后在另一个中初始化它

标签 c# partial-classes

我有一个部分类的两个部分:

public partial class Class1 : AnotherClass
{
   int id;
}

public partial class Class1
{
   public void func()
   {
      //here i need to access the id variable defined in the other part
      id = 1;   //this instruction raise an error "The name 'id' does not exists in the current context"
   }
}

我怎样才能访问那个变量?

最佳答案

您可以访问该字段,但您必须在某些方法/构造函数中访问它,您不能直接在类级别访问它。

public partial class Class1
{
   public void SomeMethod()
   {
     id = 1;
   }
}

如果您正在进行 Field 初始化,那么最好在分部类中定义一个重载的构造函数,然后像这样赋值:

public partial class Class1
{
   public Class1(int id)
   {
     this.id = id;
   }
}

关于c# - 在一个继承类的部分类中声明类字段,然后在另一个中初始化它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21337631/

相关文章:

C# 索引器和 Linq

c# - 雅虎通库 C#

ruby-on-rails - Ruby : multiple files, 一个 "require"子句

c# - 表单设计器打破了通用抽象 UserControl

c# - C# 和 Web 服务中的部分类

c# - 重定向后 ASP Net Core 2.2 session 丢失

c# - 在 WCF SOAP API 中使用 HTTP 授权 header 进行身份验证

c# - 从已安装的应用程序中获取 GUID c#

c# - 如果一个分部类继承自一个类,那么所有其他具有相同名称的分部类也应该继承相同的基类吗?