【问题标题】:Declare class field in one partial class that inherits a class, then initialize it in another在一个继承类的部分类中声明类字段,然后在另一个类中初始化它
【发布时间】:2014-01-24 16:29:18
【问题描述】:

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

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

如何访问该变量?

【问题讨论】:

  • 我编辑了标题,希望能更好地传达真正的问题。
  • 您的实际问题是,为什么需要在另一个部分声明未初始化的变量(即现在它不再是部分了)。
  • @Steve 对不起,我忘记了函数!
  • @MauriceStam 我已经简化了我的真实情况
  • 命名空间一样吗?

标签: c# partial-classes


【解决方案1】:

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

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

如果您正在进行字段初始化,那么最好在部分类中定义一个重载的构造函数,然后分配如下值:

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

【讨论】:

  • 对不起,我忘记了课程第二部分的功能。现在我已经添加了
  • @Albirex,您的方法签名错误,您应该指定返回类型而不是function,它应该类似于:public void func()。但除此之外,只要这两个类都定义在一个命名空间中,它就应该编译。
【解决方案2】:

编译器无法判断在您的示例中哪个语句是第一个。在构造函数中初始化你的类级变量。

public partial class Class1
{
   int id;
}

public partial class Class1
{
   //here i need to access the id variable defined in the other part
  public Class1()
  { 
     id = 1; 
  }
}

【讨论】:

    猜你喜欢
    • 2015-04-05
    • 2022-06-10
    • 2022-06-11
    • 2023-04-02
    • 2011-01-10
    • 2012-12-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-24
    相关资源
    最近更新 更多