2010-03-09 36 views
1

我試圖設置我的自動屬性,但它們是非靜態的,所以當嘗試設置屬性證書,證書和UrlEndPoint時,出現錯誤「無法訪問靜態上下文中的非靜態屬性」。單身人士幫助 - 設置自動屬性?

public class PayPalProfile 
{ 
    #region Fields 

    static PayPalProfile _instance; 

    #endregion 

    #region Constructors 

    PayPalProfile() 
    { 
     // is only called if a new instance is created 
     SetProfileState(); 
    } 

    #endregion 

    #region Properties 

    public static PayPalProfile CurrentProfile 
    { 
     get 
     { 
      if (_instance == null) 
       _instance = new PayPalProfile(); 

      return _instance; 
     } 
    } 

    public CustomSecurityHeaderType Credentials { get; private set; } 

    public X509Certificate2 Certificate { get; private set; } 

    public string UrlEndPoint { get; private set;} 

    #endregion 

    #region Methods 

    private static void SetProfileState() 
    { 
     // Set the profile state 
     SetApiCredentials(); 
     SetPayPalX509Certificate(); 
    } 

    private static void SetApiCredentials() 
    { 
     Credentials = new CustomSecurityHeaderType 
          { 
           Credentials = 
           { 
            Username = PayPalConfig.CurrentConfiguration.ApiUserName, 
            Password = PayPalConfig.CurrentConfiguration.ApiPassword 
           } 
          }; 

     UrlEndPoint = PayPalConfig.CurrentConfiguration.ExpressCheckoutSoapApiEndPoint; 
    } 


    private static void SetPayPalX509Certificate() 
    { 
     PayPalCerfiticate paypalCertificate = new PayPalCerfiticate(); 

     Certificate = paypalCertificate.PayPalX509Certificate; 
    } 

    #endregion 
} 

回答

2

沒有必要爲SetProfileStateSetApiCredentialsSetPayPalX509Certificate是靜態的。

SetApiCredentialsSetPayPalX509Certificate是非靜態屬性的設置值,因此需要實例。通過從上述方法中刪除靜態修飾符,當調用SetProfileState時,屬性將設置在正在構建的實例上。

0

這意味着您有一個靜態方法,您嘗試分配實例屬性。由於靜態方法/屬性中沒有可用的實例,因此會給出錯誤。

的例子:

public class Test { 
    public int InstanceProperty { get; set; } 
    public static void StaticMethod() { 
    InstanceProperty = 55; // ERROR HERE 
    } 
} 

相反博特要麼是靜態或實例背景:

public class Test { 
    public static int StaticProperty { get; set; } 
    public static void StaticMethod() { 
    StaticProperty = 55; // Ok 
    } 
} 

public class Test { 
    public int InstanceProperty { get; set; } 
    public void InstanceMethod() { 
    InstanceProperty = 55; // Ok 
    } 
}