首先,不要使用字符串代替
enum
。这可能并不明显,但您正在执行基于文化的比较,并且正在使用当前文化规则将
PaymentMethod
转换为大写。这是什么意思?土耳其语区域设置是教科书般的例子:
"ind".ToUpper() != "IND"
。如果您需要比较两个字符串而不考虑大小写,请使用
String.Equals(PaymentMethod, "IND", StringComparer.InvariantCultureIgnoreCase)
(在这里,我假设因为一个字符串是硬编码的,您想要使用固定的文化规则进行比较,但也可以使用序数比较)。
在C#中,您不需要以那种方式声明命名空间,这种语法是有效的:
namespace Something.Finance.Donations {
}
关于你的问题:使用
ref
传递的变量可能会被修改。但是,如果这个变量是不可变的(假设它是一个变量,只是想象一下...),那么就会出现编译器错误。
请阅读以下内容:
static void ChangeAnimalWithRef(ref Animal animal) {
animal = new Cat();
Debug.Assert(animal.GetType() == typeof(Cat));
}
static void ChangeAnimalWithoutRef(Animal animal) {
animal = new Cat();
Debug.Assert(animal.GetType() == typeof(Cat));
}
void Test1() {
Animal animal = new Dog();
Debug.Assert(animal.GetType() == typeof(Dog));
ChangeAnimalWith(ref animal);
Debug.Assert(animal.GetType() == typeof(Cat));
}
void Test2() {
Animal animal = new Dog();
Debug.Assert(animal.GetType() == typeof(Dog));
ChangeAnimalWithoutRef(animal);
Debug.Assert(animal.GetType() == typeof(Dog));
}
将其视为变量的指针,而不是该变量的值(在C#中,参数按值传递,需要使用
ref
和
out
来按引用传递它们)。
如果您拥有
ThisPaymentGateway.Process()
方法,我敢打赌您不需要
ref
修饰符,并且您只是习惯于使用C++中的引用和
&
。在C#中情况不同。
如果由于某种晦涩的原因,您不拥有该方法,并且其签名无法更改,则有两个选项:
1)创建一个虚拟变量:
Electronic1 dummy = this;
ThisPaymentGateway.Process(ref dummy);
Debug.Assert(Object.ReferenceEquals(dummy, this), "Ooops, what are we supposed to do?");
2)从类外部调用该函数(并稍微更改逻辑):
var obj = new Electronic1();
if (obj.CanRunController())
obj.ThisPaymentGateway.Process(ref obj);
我强烈怀疑你需要它们中的任何一个,这只是为了完整性。
RunController()
函数? - TigranProcess
需要通过ref
传递参数吗?错误信息是因为无法重新分配this
。如果您需要使用ref
传递,您需要创建一个新变量并传递它。 - LeeThisPaymentGateway.Process(this)
就可以实现。 - TJ Rockefeller