简体   繁体   English

在C#中设置类以初始化公共变量的正确方法是什么?

[英]What's the proper way to set up a class to initialize public variables in c#?

I have created the class at the bottom in c#. 我已经在C#的底部创建了该类。 This class is referenced by webservices to determine user accesses, like this: webservices引用此类来确定用户访问,例如:

[WebMethod]
public List<FAFSA> getFAFSA(string pageID)
{
    formValues fv = new formValues();
    string personID = fv.personID;
    List<FAFSA> lf = new List<FAFSA>();

    if (fv.secBlur == "no_secBlur")
    {
        FAFSA f = new FAFSA();
        f.fafsaCheck = "0";
        lf.Add(f);
    }

    ...
}

I'm trying to add the two variables fafsa and staff. 我正在尝试添加两个变量fafsa和staff。 The method getSecBlur() is returning all three values from my database for secBlur, fafsa, and staff. 方法getSecBlur()从secBlur,fafsa和staff返回我数据库中的所有三个值。 So how do I set up this class, so that the SecBlur method is only called once but populates all three of my variables so that they can be used in webservice calls? 那么,如何设置此类,使SecBlur方法仅被调用一次,却填充我的所有三个变量,以便可以在Web服务调用中使用它们? It will not work the way it is now because it says fafsa and staff need to be static, but if I make them static, then in the webservices it says that the members must be accessed with an instance reference. 它不能像现在那样工作,因为它说fafsa和staff必须是静态的,但是如果我将它们设为静态,则在webservices中它说必须使用实例引用来访问成员。

Sorry if this isn't worded to well, but I'm new to this and still trying to learn... 抱歉,如果措辞不好,但我对此并不陌生,仍在尝试学习...

public class formValues : System.Web.Services.WebService
{
    public string userName = getUserName();
    public string firstName = getFirstName();
    public string personID = getPersonID();
    public int fafsa = 0;
    public int staff = 0;
    public string secBlur = getSecBlur();

    private static string getUserDataString(int ix)
    {
        string retValue = "";

        if (HttpContext.Current.Request.IsAuthenticated)
        {
            HttpCookie authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

            if (authCookie != null)
            {
                FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

                if (ticket != null)
                {
                    string[] userData = { "" };

                    char[] delimiterChar = { '|' };
                    userData = ticket.UserData.Split(delimiterChar);
                    if (userData.Length > 1)
                        retValue = userData[ix];
                    else
                    {
                        FormsAuthentication.SignOut(); 

                        string redirUrl = "/DMC/loginNotFound.html";
                        HttpContext.Current.Response.Redirect(redirUrl, false);
                    }
                }
            }
        }

        return retValue;
    }

    private static string getUserName()
    {
        //This retrieves the person logged into windows/active directory
        WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
        //string[] fullUsername = wp.Identity.Name.Split('\\');
        string fullUsername = wp.Identity.Name;

        return fullUsername;
    }

    private static string getFirstName()
    {
        string firstName = getUserDataString(1);

        return firstName;
    }

    private static string getPersonID()
    {
        string personID = getUserDataString(0);

        return personID;
    }

    private static string getSecBlur()
    {
        string secBlur = "no_secBlur";

        string mySQL = "exec get_UserAdminStatus @personID";
        string cf = System.Configuration.ConfigurationManager.ConnectionStrings["DistrictAssessmentDWConnectionString"].ConnectionString;

        SqlConnection connection = new SqlConnection(cf);
        SqlCommand command = new SqlCommand(mySQL, connection);

        command.Parameters.AddWithValue("@personID", getUserDataString(0));

        connection.Open();

        SqlDataReader dr = command.ExecuteReader();
        DataTable dt = new DataTable();
        dt.Load(dr);
        connection.Close();

        if (dt.Rows.Count > 0)
        {
            if (dt.Rows[0]["secBlur"].ToString() == "1")
                secBlur = "secBlur";

            fafsa = Convert.ToInt32(dt.Rows[0]["fafsa"]);
            staff = Convert.ToInt32(dt.Rows[0]["staff"]);
        }

        return secBlur;
    }
}

If you give any class static, public values the so called "Static" (or type) Constructor will be called to do the initialization work before any access is done: https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/static-constructors 如果为任何类提供静态,公共值,则在完成任何访问之前,将调用所谓的“静态”(或类型)构造函数进行初始化工作: https : //docs.microsoft.com/zh-cn/dotnet/ csharp /编程指南/类和结构/静态构造函数

Another common way to do initlizsation or define default values, is to use the Factory Pattern. 初始化或定义默认值的另一种常用方法是使用工厂模式。 Afaik the Graphics Class in XNA has to adapt depending if you run ona X-Box or PC, so it uses the Factory Pattern. Xfa中的Afaik图形类必须根据在X-Box或PC上运行而进行调整,因此它使用出厂模式。

Of coruse with Web(anything) there is the whole issue with variable Scope, even for Statics. 对于Web(任何东西)来说,问题就在于变量Scope的整个问题,即使对于静态变量也是如此。 Much less local variables. 局部变量少得多。

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

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