C# 如何将委托重置为原始代码
考虑到这个代表C# 如何将委托重置为原始代码,c#,lambda,delegates,C#,Lambda,Delegates,考虑到这个代表 public class XYZ { public static Action<Profile> DoSomething = (profile) => { //some default code here return; }; } 当我需要时,如何将代码设置回原始默认代码而不复制代码?这里有一个不使用公共字段的好理由 一旦你设定它;它走了。您可以通过以下方式保留原始值: var originalActio
public class XYZ
{
public static Action<Profile> DoSomething = (profile) =>
{
//some default code here
return;
};
}
当我需要时,如何将代码设置回原始默认代码而不复制代码?这里有一个不使用公共字段的好理由 一旦你设定它;它走了。您可以通过以下方式保留原始值:
var originalAction = XYZ.DoSomething;
XYZ.DoSomething = ...;
XYZ.DoSomething = originalAction;
然而,通常依靠客户机代码来处理这个问题是个坏主意;所以如果我写这篇文章,我会把它作为一个财产公开,就像这样:
public Action<X> DoSomethingOverride {get; set;}
public Action<X> DoSomething => doSomethingOverride ?? DefaultMethod;
private void DefaultMethod (X param)
{
}
公共操作DoSomethingOverride{get;set;}
公共行动DoSomething=>doSomethingOverride??默认方法;
私有void DefaultMethod(X参数)
{
}
有许多其他的方法来处理这个问题,但都涉及到存储原始方法。所有处理此问题的好方法都将使用一个属性来确保只有声明类实际设置了DoSomething
方法,并且可以重置为默认值
撇开总数;由于这是
静态的
设置,因此该操作将影响使用该类的所有内容。这是在以后询问bug;不要那样做。也许是这样的事
public static Action<Profile> _doSomethingBase = (profile) =>
{
//some default code here
return;
};
public static Action<Profile> _doSomething = _doSomethingBase;
public static Action<Profile> DoSomething
{
get => _doSomething;
set => _doSomething = value;
}
public static void RevertDoSomething()
{
DoSomething = _doSomethingBase;
}
publicstaticaction\u doSomethingBase=(profile)=>
{
//这里有一些默认代码
返回;
};
公共静态作用_doSomething=_doSomethingBase;
公共静态作用剂量仪
{
get=>\u doSomething;
set=>\u doSomething=值;
}
公共静态无效还原dosomething()
{
DoSomething=_DoSomething基;
}
创建一个可以调用的方法,将默认值(即原始值)指定给属性。您可以从构造函数中调用该方法以确保初始化。AFAIK除非将原始方法保存在其他变量中,否则无法调用该方法。编辑:好的,Kenneth是对的。如果这是一个临时交换,你也可以将原始的赋值给一个变量,然后再重新赋值。但这取决于您如何使用它。这不是特定于代理的,如果变量是int
或字符串,则答案是相同的。我可以获得否决票,但没有解释就很难纠正错误。知道为什么吗?同意静态评论。不过,在这种情况下,这不是一个问题。
public static Action<Profile> _doSomethingBase = (profile) =>
{
//some default code here
return;
};
public static Action<Profile> _doSomething = _doSomethingBase;
public static Action<Profile> DoSomething
{
get => _doSomething;
set => _doSomething = value;
}
public static void RevertDoSomething()
{
DoSomething = _doSomethingBase;
}