【发布时间】:2019-11-18 15:28:07
【问题描述】:
我正在尝试创建一个接口,该接口的属性可能是Action 或Action<T> 作为实际实现。传入的方法有些不需要参数,有些则需要。
在研究和尝试了几种方法之后,我来到了这里:
using System;
using System.Collections.Generic;
namespace InterfaceProperty
{
class Program
{
static void Main(string[] args)
{
var ClassItems = new List<SomeClass>()
{
new SomeClass() { TitleProp = "Foo" },
new SomeClass() { TitleProp = "Bar" }
};
#region Simple
var SimpleActions = new List<SimpleAction>()
{
new SimpleAction() { Title = "Foo", Action = MethodWithoutParam },
new SimpleAction() { Title = "Bar", Action = MethodWithoutParam }
};
foreach (var item in ClassItems)
{
// In "real life" this would be triggered in an event, and the parent loop would not be required.
foreach (var simpleAction in SimpleActions)
{
if (simpleAction.Title == item.TitleProp)
{
simpleAction.Action();
}
}
}
#endregion
#region Complicated
var ComplicatedActions = new List<IGenericAction<Action>>()
{
new GenericAction<Action>() { Title = "Foo", Action = MethodWithoutParam },
new GenericAction<Action<string>>() { Title = "Bar", Action = MethodWithParam } // fails here
};
foreach (var item in ClassItems)
{
// In "real life" this would be triggered in an event, and the parent loop would not be required.
foreach (var genericAction in ComplicatedActions)
{
if (genericAction.Title == item.TitleProp)
{
genericAction.Action();
}
}
}
#endregion
Console.ReadLine();
}
private static void MethodWithoutParam()
{
Console.WriteLine("Method without a parameter");
}
private static void MethodWithParam(string param)
{
Console.WriteLine($"Method with parameter: {param}");
}
}
public class SomeClass
{
public string TitleProp { get; set; }
}
#region Simple
public class SimpleAction
{
public string Title { get; set; }
public Action Action { get; set; }
}
#endregion
#region Complicated
public interface IGenericAction<T>
{
string Title { get; set; }
T Action { get; set; }
}
public class GenericAction<T> : IGenericAction<T>
{
public string Title { get; set; }
public T Action { get; set; }
}
#endregion
}
必须将T 参数作为Action 或Action<T> 传递是创建属性Action 的泛型类型列表的问题。
这个的真正实现用在 UI 自动化的过程中。我正在连接一个AutomationElement,并监听WindowPattern.WindowOpening 事件,这是触发内部foreach 循环的地方。这个想法是,有一个预定义的要监听的窗口列表,以及一个在打开该窗口时调用的方法。其中一些方法需要一个参数,而另一些则不需要 - 因此Action vs Action<T>。
我真的可以朝正确的方向轻推。
编辑: 包含简单区域是因为那是当前代码,我将其作为我试图到达的上下文提供。
【问题讨论】:
-
一种方法是使用
Delegate而不是Action和Action<T>- 那么你就不需要SimpleAction、IGenericAction<T>和GenericAction<T> -
你从哪里得到
Action<T>的参数?除非它需要来自委托的调用者,否则您可能希望在外部关闭它(例如() => MethodWithParam("My parameter"),它给您Action,而不是Action<string>)。
标签: c# generics automation