繁体   English   中英

如何从另一个类 C#/MVC 访问属性

[英]How to Access to a property from another class C#/MVC

基本上问题是我需要访问类中的当前用户身份。 我在 MVC 控制器中得到它很好,但我需要能够在类中访问。 所以我试图使用属性来设置它,但无法弄清楚 get 部分。 这是代码:

//Employee.cs  
public class CurrUser
    {
        public string USERID{ get; set; }

    }

MVC控制器:

//HomeController
        public async Task<JsonResult> GetDefaultMgrGeid()
        {
            string Soeid = User.Identity.Name.Split("\\".ToCharArray())[1];
            //setting prop here
            CurrUser emp = new CurrUser();
            emp.USERID = Userid;

            var task = Task.Run(() => DAL.Employee.GetDefaultMgr(Soeid));

            var retData = await task;
            return new JsonResult
            {
                ContentType = "application/json",
                Data = retData,
                JsonRequestBehavior = JsonRequestBehavior.AllowGet,
                MaxJsonLength = int.MaxValue
            };
        }

我需要访问(获取)此处的值:

public class HR
    {
    // I tried this but did not work either
        // public CurrUser user{ get; set; }
        //  public string GetUser
        //  {
        //      get
        //     {
        //          return user.USERID;
        //     }
        //  }
       public static IEnumerable<DTO.Employee> GetGlobalMgrs()
        {
         string mrgID = CurrUser.??;// I can't access it here
        }

}

请指导!

改成这样:

    public class HR
    {
       //by setting this property to static your static methods in this class can access it
       public static CurrUser user{ get; set; }

       public static IEnumerable<DTO.Employee> GetGlobalMgrs()
       {
         string mrgID = user.USERID;
         //put your other code here like retrieving the list
       }
    }

如果您需要从其他类访问它:

这样做: Hr.user确保您using正确的命名空间

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM