[英]Share variables between projects
我有一些项目的解决方案。 其中一个项目是我定义为main的项目,他的班级也有一个主要的方法。
在这个类中,我已经定义了一些属性public和static。 我想要的是从其他项目文件访问此属性。 例如:
项目A:
namespace Cobra
{
public static class Program
{
public static int A;
public static int B;
...
项目B:
namespace Net
{
public class HttpHandler : IHttpHandler
{
...
public void ProcessRequest()
int a =Cobra.Program.A;
int b =Cobra.Program.B;
...
我怎样才能做到这一点??
编辑:
如果我在项目B中添加项目A作为参考: “添加此项目作为参考,将存在循环依赖。”
项目B包含一些其他文件,因此需要在项目A中引用项目B.
在项目B中,添加对项目A的引用,并将using Cobra
语句添加到项目B,无论您要从Cobra(项目A)命名空间访问某些内容。
基于您对其他答案的评论,听起来您的问题实际上是您有一个循环依赖,您需要打破。 通常,这样做的方法是分解一个接口并将其放在第三个项目中,其他项目都可以引用它而不是
class Foo //foo lives in project 1 (depends on project 2)
{
public Bar GetNewBar()
{
return new Bar(this);
}
public void DoSomething(){}
}
public class Bar //bar lives in project 2 (depends on project 1 -- cant do this)
{
public Bar(Foo parent){}
}
你有
class Foo: IFoo //foo lives in project 1 (depends on project 2 and 3)
{
public Bar GetNewBar()
{
return new Bar(this);
}
public void DoSomething(){}
}
public class Bar //bar lives in project 2 (depends on project 3)
{
public Bar(IFoo parent){}
}
public interface IFoo //IFoo lives in project 3 (depends on nothing)
{
void DoSomething();
}
@Manu,
通过反思是可能的。 以下是您的问题的解决方案。
您已创建了2个项目
项目B - 名称空间为“Net”,类为“HttpHandler”
项目A - 具有名称空间“cobra”,静态类“程序”并参考项目B.
现在您的问题是您需要访问项目B中的“程序”类而不将项目A引用到项目B,因为这样解决方案将不会构建,因为它将给出循环引用错误。
请查看以下内容
项目A.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Net; namespace Cobra { public static class Program { public static int A { get; set; }//Getter/Setter is important else "GetProperties" will not be able to detect it public static int B { get; set; } static void Main(string[] args) { HttpHandler obj = new HttpHandler(); obj.ProcessRequest(typeof(Program)); } } }
项目B.
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Net { public class HttpHandler : IHttpHandler { public void ProcessRequest(Type cobraType) { int a, b; foreach (var item in cobraType.GetProperties(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)) { if (item.Name == "A") a = (int)item.GetValue(null, null);//Since it is a static class pass null else if (item.Name == "B") b = (int)item.GetValue(null, null); } } } }
希望这个对你有帮助。
问候,
萨马
您需要在项目B的文件顶部添加using指令:
using Cobra;
并在项目B中添加项目A作为参考。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.