Share variables between projects

后端 未结 5 823
天命终不由人
天命终不由人 2021-01-05 22:04

I have a solution with some projects. One of this projects is the one I\'ve defined as main, also his class has a main Method.

Inside this class, I\'ve defined some

5条回答
  •  鱼传尺愫
    2021-01-05 22:42

    @Manu,

    It is possible through reflection. The following is the solution to your problem.

    You have created 2 projects

    Project B -- having namespace "Net", class "HttpHandler"

    Project A -- having namespace "cobra", static class "Program" and having reference of Project B

    Now your problem is you need to access the class "Program" in Project B without giving reference of Project A to Project B because then the solution will not build as it will give cyclic reference error.

    Check out the following

    Project 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));
            }
        }
    }
    
    
    

    Project 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);
                }
            }
        }
    }
    
    
    

    Hope this is of some help.

    Regards,

    Samar

提交回复
热议问题