C# 重写GetEnumerator的默认行为
我需要知道调用C# 重写GetEnumerator的默认行为,c#,list,ienumerable,ienumerator,callermembername,C#,List,Ienumerable,Ienumerator,Callermembername,我需要知道调用GetEnumerator()的方法 我所能想到的最好的方法可能是将GetEnumerator的默认行为重写为我创建的行为,即GetEnumerator([CallerMemberName]string caller=null),但我似乎无法这样做,因为调用它的任何东西都会转到原始行为 public class MyItems : IEnumerable<string> { private List<string> items = new List&
GetEnumerator()
的方法
我所能想到的最好的方法可能是将GetEnumerator
的默认行为重写为我创建的行为,即GetEnumerator([CallerMemberName]string caller=null)
,但我似乎无法这样做,因为调用它的任何东西都会转到原始行为
public class MyItems : IEnumerable<string>
{
private List<string> items = new List<string>();
public MyItems()
{
items.Add("One");
items.Add("Two");
items.Add("Three");
items.Add("Four");
items.Add("Five");
items.Add("Six");
}
public IEnumerator<string> GetEnumerator()
{
return items.GetEnumerator();
}
public IEnumerator<string> GetEnumerator([CallerMemberName]string caller = null)
{
var method = caller;
return items.GetEnumerator();
}
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{
throw new NotImplementedException();
}
}
我的目的是想知道,例如,
GetEnumerator()
方法中的按钮1\u单击“
”我认为不可能准确地执行您想要执行的操作,因为据我所知,foreach
总是在没有任何参数的情况下调用GetEnumerator()
。然而,我认为你的问题有两种可能性
您可以使用来获取调用方法:
public IEnumerator<string> GetEnumerator()
{
StackTrace stackTrace = new StackTrace();
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);
return items.GetEnumerator();
}
看起来,您需要使用StackTrace类
StackTrace st = new StackTrace();
var fr = st.GetFrames();
if(fr != null && fr.Any() &&fr.Count() >1)
{
MessageBox.Show(fr.ElementAt(1).GetMethod().Name);
}
调用方代码是什么样子的?不要直接实现IEnumerable。相反,使用一个方法GetEnumerable(string caller)返回IEnumerable并将调用方作为参数。不实现IEnumerable不是一个选项,因为我们正在实现一个已经实现IEnumerable的接口。该接口是Microsoft IDBSet接口。我们需要从通用存储库中了解调用方法,以便做出相应的反应,但希望保持存储库层和数据库集等之间的分离。StackFrame方法适用于
foreach()
,但请注意,在项中,Where(…)
将给出“Where”
作为调用方名称。@Guillaume您是指带有StackTrace
的第一个方法吗?@Default是的,这就是我的意思Any()
不意味着有超过0个元素吗?您真的需要检查Count
(如果需要,不应该是>0
)?Count()>1用于防止fr.ElementAt(1)如果只有一个帧会抛出异常,则不需要调用Any()
public IEnumerable<string> Iterate([CallerMemberName]string caller = null)
{
Console.WriteLine(caller);
return items;
}
foreach (var myItem in items.Iterate())
{
//..
}
StackTrace st = new StackTrace();
var fr = st.GetFrames();
if(fr != null && fr.Any() &&fr.Count() >1)
{
MessageBox.Show(fr.ElementAt(1).GetMethod().Name);
}