c#方法作为参数,其中方法包含ref参数
c#方法作为参数,其中方法包含ref参数,c#,C#,我有下面的方法
public static void Method1(ref List<int> list)
{//code to update list}
公共静态无效方法1(参考列表)
{//更新列表的代码}
是否可以创建一个将此方法作为参数的方法,类似于(但不是使用Action,而是使用Action)
publicstaticvoidmethod2(Action-otherMethod)
{var newList=newList();otherMethod(newList)
我有下面的方法
public static void Method1(ref List<int> list)
{//code to update list}
公共静态无效方法1(参考列表)
{//更新列表的代码}
是否可以创建一个将此方法作为参数的方法,类似于(但不是使用Action,而是使用Action[)
]publicstaticvoidmethod2(Action-otherMethod)
{var newList=newList();otherMethod(newList)}
我的主要问题是,我的方法使用引用,而Action>不使用引用。这可能吗?类应用程序
class App
{
private readonly Dictionary<Type, object> delegateMap;
void Add<T>(Action<SomeClass<T>> foo)
{
object tmp;
if (!delegateMap.TryGetValue(typeof(T), out tmp))
{
tmp = new List<Action<SomeClass<T>>>();
delegateMap[typeof(t)] = tmp;
}
List<Action<SomeClass<T>> list = (List<Action<SomeClass<T>>) tmp;
list.Add(foo);
}
void InvokeActions<T>(SomeClass<T> item)
{
object tmp;
if (delegateMap.TryGetValue(typeof(T), out tmp))
{
List<Action<SomeClass<T>> list = (List<Action<SomeClass<T>>) tmp;
foreach (var action in list)
{
action(item);
}
}
}
}
{
私有只读字典delegateMap;
无效添加(操作foo)
{
对象tmp;
如果(!delegateMap.TryGetValue(类型(T),输出tmp))
{
tmp=新列表();
委派地图[类型(t)]=tmp;
}
List是,但不能使用操作
/函数
为此,必须“手动”生成委托:
//您的方法
公共静态无效方法1(参考列表)
{
}
//代表
公共代表无效方法1删除(参考列表);
//接受委托并使用它的方法
公共静态无效方法2(方法1删除)
{
List=null;
del(参考列表);
}
噢,我很想看到方法1的实现,然后剖析为什么ref
我们完全没有必要……这解决了我的问题,谢谢:)
class App
{
private readonly Dictionary<Type, object> delegateMap;
void Add<T>(Action<SomeClass<T>> foo)
{
object tmp;
if (!delegateMap.TryGetValue(typeof(T), out tmp))
{
tmp = new List<Action<SomeClass<T>>>();
delegateMap[typeof(t)] = tmp;
}
List<Action<SomeClass<T>> list = (List<Action<SomeClass<T>>) tmp;
list.Add(foo);
}
void InvokeActions<T>(SomeClass<T> item)
{
object tmp;
if (delegateMap.TryGetValue(typeof(T), out tmp))
{
List<Action<SomeClass<T>> list = (List<Action<SomeClass<T>>) tmp;
foreach (var action in list)
{
action(item);
}
}
}
}
// Your method
public static void Method1(ref List<int> list)
{
}
// The delegate
public delegate void Method1Delegate(ref List<int> list);
// A method that accepts the delegate and uses it
public static void Method2(Method1Delegate del)
{
List<int> list = null;
del(ref list);
}