我的程序构造函数的属性/访问器方法中有类似的东西。
using System;
namespace BusinessTrips
{
public class Expense
{
private string paymentMethod;
public Expense()
{
}
public Expense(string pmtMthd)
{
paymentMethod = pmtMthd;
}
//This is where things get problematic
public string PaymentMethod
{
get
{
return paymentMethod;
}
set
{
if (string.IsNullOrWhiteSpace(" "))
paymentMethod = "~~unspecified~~";
else paymentMethod = value;
}
}
}
}
当输入新属性时,对于PaymentMethod(null或空格),这显然不起作用。有什么想法吗?
答案 0 :(得分:5)
您是否只需要将string.IsNullOrWhiteSpace(" ")
替换为string.IsNullOrWhiteSpace(value)
?
根据您发布的代码,您需要致电:
this.PaymentMethod = pmtMthd;
而不是
paymentMethod = pmtMthd;
首都 p 将直接使用您的属性而不是字符串。这就是为什么在访问类变量时使用this.
是个好主意。在这种情况下,资本而不是this.
会产生差异,但我会习惯使用this.
答案 1 :(得分:1)
但是这里是完整的代码,我在LinqPad中测试它以证明它有效。
public class Foo {
private string _paymentMethod = "~~unspecified~~";
public string PaymentMethod
{
get
{
return _paymentMethod;
}
set
{
if (string.IsNullOrWhiteSpace(value))
_paymentMethod = "~~unspecified~~";
else _paymentMethod = value;
}
}
}
主要是:
void Main()
{
var f = new Foo();
f.PaymentMethod = "";
Console.WriteLine(f.PaymentMethod);
f.PaymentMethod = " ";
Console.WriteLine(f.PaymentMethod);
f.PaymentMethod = "FooBar";
Console.WriteLine(f.PaymentMethod);
}
来自控制台的输出:
~~unspecified~~
~~unspecified~~
FooBar