我有一个名为CreateNode()的方法。它所做的只是创建一个XElement并返回它。我有两个调用此方法的对象:Action和ElseAction:
var x1 = Action.CreateNode();
var x2 = ElseAction.CreateNode();
这两个对象都是Action
类型,CreateNode()方法位于Action
类中。
在CreateNode()方法中,我有一行创建根XElement:
var xelement = new XElement("actionitem");
我想做的是确定Action或ElseAction是否调用CreateNode()方法,以便在调用者是ElseAction时执行以下操作:
var xelement = new XElement("elseactionitem");
所以,我想我的问题是“我可以确定调用CreateNode方法的人/名称吗?”我可以做以下事情吗?:
if (caller == Action) var xelement = new XElement("actionitem");
if (caller = ElseAction) var xelement = new XElement("elseactionitem");
答案 0 :(得分:1)
在.net 4.5中很容易做到。
如果有如下方法:
public void doAction([CallerMemberName] string fromWhere ="")
{
}
如果调用doAction,将从调用它的方法填充字符串。 callerMemberName
答案 1 :(得分:1)
有不同的方法可以做到这一点。最好的是:
class Action
{
public virtual XElement CreateNode() {return new XElement("actionitem");}
};
class ElseAction : Action
{
public override XElement CreateNode() {return new XElement("elseactionitem");}
};
答案 2 :(得分:0)
答案 3 :(得分:0)
您可以检查对象(Action或ElseAction),并通过执行以下操作调用适当的方法:
if (caller is Action) {
// Logic goes here if the caller is of type 'Action'
// you can use the item as an 'Action' type like
(caller as Action).SomeMethodOfAction();
} else if (caller is ElseAction) {
// Logic goes here if the caller is of type 'ElseAction'
(caller as ElseAction).SomeMethodOfElseAction();
}