我有很多类反射(reflect)了 White/UIAutomation 的屏幕存储库。 要使用存储库,我需要创建许多反射(reflect)应用程序窗口屏幕的类。
要创建存储库,我使用以下方法:
var repoReport = repository.Get<MyClassRepresentingWindow>("WindowTitle",
InitializeOption.WithCache);
它传递一个泛型类型,该类型是 I 类准备的。
我想要做的是创建一个 Dictionary(stringClassName, string windowTitle) 或任何映射来传递给该方法。 问题是无法像 Java ClassForName 那样传递 className。
我试过System.Activator
但没有任何成功。
Object configObj = System.Activator.CreateInstance(c);
Type c = System.Type.GetType("Namespace.MyClassRepresentingWIndow");
var myClass = System.Reflection.Assembly.GetExecutingAssembly().CreateInstance("Namespace.MyClassRepresentingWIndow");
Type type = assembly.GetType("Namespace.MyClassRepresentingWIndow");
object obj = Activator.CreateInstance(type);
var repoReport = repository.Get<c>("WindowTitle",
InitializeOption.WithCache);
var repoReport = repository.Get<c.Name>("WindowTitle",
InitializeOption.WithCache);
更新1 伙计们,我不会坐在代码前面,但我会尽力使我的问题不那么复杂。
这是我在 White 存储库中找到的一种方法,我认为我使用过: https://github.com/petmongrels/white/blob/itemsmap/Components/Repository/Source/ScreenRepository.cs
public virtual T Get<T>(string title, InitializeOption option) where T : AppScreen
{
ClearClosedScreens();
AppScreen screen;
var repositoryCacheKey = new ScreenRepositoryCacheKey(title, typeof (T));
if (!screenCache.TryGetValue(repositoryCacheKey, out screen))
{
Window window = applicationSession.Application.GetWindow(title, IdentifiedOption<T>(option));
screen = GetScreen<T>(window);
screenCache.Add(repositoryCacheKey, screen);
}
if (screen != null)
sessionReport.Next(typeof (T));
return (T) screen;
}
我记得 VS 将 .Get 显示为 .Get<"class"type>。很抱歉我无法更好地表达自己。请有一位病人陪我,因为我不熟悉这个术语。
更新2
最后我想要得到这样的东西:
var repoReport1 = repository.Get<MyClassRepresentingWindow1>("WindowTitle", InitializeOption.WithCache);
var repoReport1 = repository.Get<MyClassRepresentingWindow2>("WindowTitle", InitializeOption.WithCache);
var repoReport1 = repository.Get<MyClassRepresentingWindow3>("WindowTitle", InitializeOption.WithCache);
我的代码是MyClassRepresentingWindow{1,2,3}
。我只是不知道如何将类名传递给 Get 方法。输入时我有这个类的字符串名称。在输出时,我想提供此方法 .Get<T>
的东西可以得到。
我希望你现在能理解我。
最佳答案
为了使用变量类型参数调用此参数(其值仅在运行时才知道),您需要使用反射。我假设您知道如何获取 MethodInfo
代表存储库的 Get<T>
方法。
一旦您了解了这一点,此示例将说明如何使用 MethodInfo 对象的基本思想。该示例假设 repository
类名为 Repo
;根据需要更改:
object InvokeGenericMethod(Repo repository, MethodInfo method, Type typeArg, string arg1, InitializeOption arg2)
{
MethodInfo constructedMethod = method.MakeGenericMethod(typeArg);
return constructedMethod.Invoke(repository, new object[] { arg1, arg2 });
}
当然,您可以使其更加通用,但这会使示例变得不太清晰。
关于c# - 如何在 C# 中将 className 传递给将泛型类型作为参数的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8606811/