我正在尝试设置自动属性,但它们是非静态的,因此在尝试设置属性凭据,证书和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
}
答案 0 :(得分:2)
SetProfileState
,SetApiCredentials
和SetPayPalX509Certificate
不需要是静态的。
SetApiCredentials
和SetPayPalX509Certificate
是非静态属性的设置值,因此需要一个实例。通过从上述方法中删除静态修饰符,将在调用SetProfileState
时在正构造的实例上设置属性。
答案 1 :(得分: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
}
}