[英]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.