2012-06-09 2 views
3

응용 프로그램에서 ASP.NET Web Forms 및 C#을 사용하고 있습니다. 나는 이라는 이름의 클래스 파일을 가지고 있는데, 여기서 나는 setget 속성을 사용하여 변수를 정의한다. 그 클래스 객체를 인스턴스화하여 페이지의 아무 곳에 나 변수를 사용합니다.ASP.NET에서 C# 전역 변수를 사용하는 올바른 방법은 무엇입니까?

using System; 
using System.Data; 
using System.Linq; 
using System.Web; 

/// <summary> 
/// Contains my site's global variables. 
/// </summary> 
public static class Global 
{ 
    /// <summary> 
    /// Global variable storing important stuff. 
    /// </summary> 
    public static string gDate; 
    public static string gMobLength; 
    public static string gDateFormat; 
    public static string gApplicationNo; 
    public static string gBranchNo; 
    public static string gMemId; 
    public static string gIsEditable="false"; 
    public static string gLoggedInUserName; 


    public static string ImportantData 
    { 
     get 
     { 
      return gDate; 

     } 
     set 
     { 
      gDate = value; 

     } 

    } 
    public static string MobileLength 
    { 
     get 
     { 
      return gMobLength; 
     } 
     set 
     { 
      gMobLength = value; 
     } 
    } 

    public static string DateFormat 
    { 
     get 
     { 
      return gDateFormat; 
     } 
     set 
     { 
      gDateFormat = value; 
     } 
    } 
    public static string ApplicationNo 
    { 
     get 
     { 
      return gApplicationNo; 
     } 
     set 
     { 
      gApplicationNo = value; 
     } 
    } 
    public static string BranchNo 
    { 
     get 
     { 
      return gBranchNo; 
     } 
     set 
     { 
      gBranchNo = value; 
     } 
    } 

} 

이 프로젝트를 통해 변수를 사용하는 적절한 방법인가 : 내 Global.cs 파일은 여기에

입니까? 이 접근법의 장단점은 무엇이며 전역 변수를 사용하기 위해 어떤 접근 방식을 취하고 있습니까?

답변

4

먼저 PSM, 나는 autoimplemented 속성을 사용하는 것이 좋습니다 것입니다.

public static string BranchNo { get; set; } 

코드를 약간 간소화하십시오. 이것이 좋은 접근 방법인지 여부에 따라 다르다. 때로는 단순하고 똑바로 전진하는 것이 더 좋으며, 이것은 그 범주에 속합니다.

public class Settings 
{ 
    private static Settings _current; 
    private static readonly object _lock = new object(); 

    public static Settings Current 
    { 
     get 
     { 
     lock(_lock) 
     { 
      if (_current == null) throw new InvalidOperationException("Settings uninitialized"); 
      return _current; 
     } 
     } 
     set 
     { 
      if (value == null) throw new ArgumentNullException(); 
      if (_current != null) throw new InvalidOperationException("Current settings can only be set once."); 

      if (_current == null) 
      { 
       lock(_lock) 
       { 
       if (_current == null) _current = value; 
       } 
      } 
     } 
    } 


    public string ImportantData { get; private set; } 

    // etc. 
} 

초기화 설정 :

Settings.Current = new Settings{ ImportantData = "blah blah blah"}; 

액세스 :

var data = Settings.Current.ImportantData; 
+1

그래도이 스레드는 안전합니까? – McGarnagle

+0

@HackedByChinese 제안을 주셔서 감사합니다. 내 접근 방식과 내 코드를 단순화하기 위해 제안한 접근 방식의 차이점은 무엇입니까? 감사합니다. – freebird

+0

자동 구현 된 속성은 자동으로 뒷받침 필드를 생성하므로 소스에 포함하지 않아도됩니다. – HackedByChinese

2

두 개 외부 bromides "전역이 좋지 않음"이고 "properties이 좋다"... 내재적으로 잘못된 것은 없습니다. 어서가!

이럴 ..

+0

조언을 주셔서 감사합니다. IMHO PSM이 무엇인지 물어봐도 되겠습니까? 어리석은 소리 일 수 있습니다. 감사합니다. – freebird

+0

"PSM"은 제 이름입니다 :). "IMHO"는 "내 겸손한 견해"를 의미합니다. 그리고 솔직히 당신이 이미 속성을 사용하고 있다는 사실을 알지 못했습니다. 나는 여러분에게 방금 공개 정적 변수가 있다고 생각했습니다. 어느 IMHO가 완벽하게 괜찮을 수 있습니다. – paulsm4

+0

:) 고맙습니다. 배울 점이 많습니다. 감사합니다. – freebird

1

이유 이유를 값이 한 번 초기화 변경해서는 안 경우에는 초기에 적절한 싱글 톤을 사용할 수 있습니다 변수가 정적으로 선언 되었기 때문에 해당 클래스 객체를 인스턴스화 한 후에 변수가 표시되지 않습니다. 정적 변수는 해당 매너에서 사용하기위한 것입니다. ClassName.variableName 또는 ClassName.PropertyName

관련 문제