我试图做一个简单的字符串扩展,将更改分配给原始字符串(如toUpper)。在这种情况下,如果方法既不是空格也不为null,则该方法将内容分配给第二个参数...否则将当前值保留在适当的位置,或将空值分配给“”。所以,我想拥有它:
somerecord.Property1.func(someobj.property);
somerecord.Property2.func(someobj.otherproperty);
somerecord.Property3.func(someobj.anotherproperty);
而我的代码看起来像
public static string func(this String str, string replacement)
{
if (!String.IsNullOrWhiteSpace(replacement)) {
str = replacement;
return replacement;
}
else
{
if(str == null)
str = "";
return "";
}
}
我想设置this
为,ref
但不能。关于如何干净地实现这一点的任何想法?
不要将方法设为扩展方法,而要实现常规的静态方法:
public static void func(ref string str, string replacement)
{
if (!String.IsNullOrWhiteSpace(replacement)) {
str = replacement;
}
else
{
if(str == null)
str = "";
}
}
但是请注意,您的用例仍然无法使用,您不能将属性作为ref
参数开头:
class Foo
{
public string someVariable;
public string SomeProperty { get; }
}
var foo = new Foo();
func(ref foo.someVariable, ""); //ok
func(ref foo.SomeProperty, ""); //compile time error
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句