【问题标题】:Unable to access public type members in another assembly. I have two assemblies, I want to access public members from one assembly in another assembly无法访问另一个程序集中的公共类型成员。我有两个程序集,我想从另一个程序集中的一个程序集访问公共成员
【发布时间】:2021-12-04 02:57:17
【问题描述】:
using System;

namespace AssemblyOne
{

    public class AssemblyOneClassOne
    {
        protected internal int ID = 101;
        public int id = 102;
        public void Print() 
        {
            Console.WriteLine("Abdullah is a handsome hunk!");
        }
    }
    public class AssemblyOneClassTwo 
    {
        public void SampleMethod() 
        {
            AssemblyOneClassOne a1 = new AssemblyOneClassOne();
            Console.WriteLine(a1.ID);
        }
    }
    public class A
    { 
        public static void Main()
        {
            AssemblyOneClassTwo a2 = new AssemblyOneClassTwo();
            a2.SampleMethod();
            Console.ReadKey();
        }
    }
}
using System;
using AssemblyOne;

namespace AssemblyTwo

{

    public class AssemblyTwoClassOne
    { 
        AssemblyOneClassOne instance = new AssemblyOneClassOne();
        instance.Print();//Over here I am getting compile time error, 'instance' does not exist in the current context, 'instance.Print' does not exist in the current context
    }
}

据我所知,公共类型可以在同一个程序集以及另一个程序集中的任何地方访问

【问题讨论】:

  • instance.Print(); 位于 AssemblyTwoClassOne 类的根目录中。那应该在方法或构造函数之类的内部

标签: c# .net access-modifiers


【解决方案1】:

是的,可以从另一个程序集访问公共类型,但您的方法 Print() 应该在类 AssemblyTwoClassOne 的方法中调用。

类似的东西-

namespace AssemblyTwo
{
    public class AssemblyTwoClassOne
    {
        AssemblyOneClassOne instance = new();
        public void Method() => instance.Print();
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-03-25
    • 1970-01-01
    • 2011-09-02
    • 2012-07-24
    • 1970-01-01
    • 2014-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多