【问题标题】:Create an instance of a class from another package从另一个包创建一个类的实例
【发布时间】:2020-04-23 08:02:52
【问题描述】:
using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace assign_5.model
    {
        class Person
        {
       public void t()
            {
                Console.WriteLine("try");
            }
      public string h()
        {
            return "ll";
        }
        }
    }





 using assign_5.model;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading.Tasks;

    namespace assign_5.Controller
    {
        class FirstNameController
        {
            Person p = new Person();
            p.t();
            string o = p.h();
     }}

为什么 p.t() 有错误;和字符串 o = p.h(); "错误 CS0236 字段初始化程序无法引用非静态字段、方法或属性 'FirstNameController.p'assign_5"

【问题讨论】:

  • 看看public void t() 是如何作为其类内部的方法存在的?问问自己 - FirstNameController 中的等效方法在哪里(提示 - 你忘了添加它)?
  • 把PUBLIC放在全班前面。

标签: c#


【解决方案1】:

您需要将您的代码移动到类中的method,同时将类Person 设置为public,以便可以从另一个命名空间访问

public class Person{}

class FirstNameController
 {
   void test(){
       Person p = new Person();
       p.t();
       string o = p.h();
   }
}

【讨论】:

  • 以后考虑将其标记为现有问题的副本。这是一个常见问题,我们可能不需要其他答案。 :)
  • 谢谢你的回答,是的,我现在记得了,只有在主课我才可以直接调用它,我对此感到困惑,谢谢。
猜你喜欢
  • 1970-01-01
  • 2016-08-25
  • 1970-01-01
  • 2020-10-23
  • 2018-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-10-16
相关资源
最近更新 更多