在项目之间共享变量
我有一些项目的解决方案。 其中一个项目是我定义为main的项目,他的class级也有一个主要的方法。
在这个类中,我已经定义了一些属性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)命名空间访问某些内容。
您需要将项目A的引用添加到项目B – 右键单击解决方案资源管理器中的项目节点,选择引用,然后选择项目,然后选择项目A.
然后,您将可以访问项目A中的所有类型。
请参阅MSDN上的此操作方法。
基于您对其他答案的评论,听起来您的问题实际上是您有一个循环依赖,您需要打破。 通常,这样做的方法是分解一个接口并将其放在第三个项目中,其他项目都可以引用它而不是
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.
使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用System.Text; 使用网络; 命名空间眼镜蛇 { 公共静态课程 { public static int A {get; 组; } // Getter / Setter很重要,否则“GetProperties”将无法检测到它 public static int B {get; 组; } static void Main(string [] args) { HttpHandler obj = new HttpHandler(); obj.ProcessRequest(typeof运算(方案)); } } }
项目B.
使用系统; 使用System.Collections.Generic; 使用System.Linq; 使用System.Text; 使用System.Reflection; 命名空间网 { 公共类HttpHandler:IHttpHandler { public void ProcessRequest(Type cobraType) { int a,b; foreach(cobraType.GetProperties中的var项(BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy)) { if(item.Name ==“A”) a =(int)item.GetValue(null,null); //因为它是静态类,所以传递null 否则if(item.Name ==“B”) b =(int)item.GetValue(null,null); } } } }
希望这个对你有帮助。
问候,
萨马
您需要在项目B的文件顶部添加using指令:
using Cobra;
并在项目B中添加项目A作为参考。