C# 单例帮助-设置自动属性?
我正在尝试设置自动属性,但它们是非静态的,因此在尝试设置属性凭据、证书和URL端点时出现错误“无法在静态上下文中访问非静态属性”C# 单例帮助-设置自动属性?,c#,C#,我正在尝试设置自动属性,但它们是非静态的,因此在尝试设置属性凭据、证书和URL端点时出现错误“无法在静态上下文中访问非静态属性” public class PayPalProfile { #region Fields static PayPalProfile _instance; #endregion #region Constructors PayPalProfile() { // is only called if a
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
}
这意味着您有一个静态方法,尝试在其中分配实例属性。由于静态方法/属性中没有可用的实例,因此给出了错误 例如:
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
}
}
SetProfileState
、SetApiCredentials
和SetPayPalX509Certificate
不需要是静态的
SetApiCredentials
和SetPayPalX509Certificate
是非静态属性的设置值,因此需要一个实例。通过从上述方法中删除静态修饰符,当调用SetProfileState
时,将在正在构造的实例上设置属性