假设存在如下所述的类X,如何获取非泛型方法的方法信息?下面的代码将引发异常.
using System;
class Program {
static void Main(string[] args) {
var mi = Type.GetType("X").GetMethod("Y"); // Ambiguous match found.
Console.WriteLine(mi.ToString());
}
}
class X {
public void Y() {
Console.WriteLine("I want this one");
}
public void Y<T>() {
Console.WriteLine("Not this one");
}
}
Run Code Online (Sandbox Code Playgroud) 如何在Powershell中调用自定义类的通用静态方法?
鉴于以下课程:
public class Sample
{
public static string MyMethod<T>( string anArgument )
{
return string.Format( "Generic type is {0} with argument {1}", typeof(T), anArgument );
}
}
Run Code Online (Sandbox Code Playgroud)
这被编译成一个程序集'Classes.dll'并加载到PowerShell中,如下所示:
Add-Type -Path "Classes.dll"
Run Code Online (Sandbox Code Playgroud)
调用MyMethod方法最简单的方法是什么?
Powershel的仿制药非常令人困惑.要实例化一个简单的列表,你需要用手鼓跳舞:
$type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$type= $type.MakeGenericType("System.string" -as "Type")
$o = [Activator]::CreateInstance($type)
Run Code Online (Sandbox Code Playgroud)
但是,如果我需要更复杂的东西<Dictionary<string,List<Foo>>,例如:
或者例如这里: Dictionary<string,List<string>>
$listType = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
$listType = $listType.MakeGenericType("System.string" -as "Type")
$L = [Activator]::CreateInstance($listType)
$dicType = ("System.Collections.Generic.Dictionary"+'`'+"2") -as "Type"
#the next line is problematic
$dicType = $dicType.MakeGenericType(
@( ("system.string" -as "Type"),
("System.Collections.Generic.List" as "Type)) # and that's of course wrong
)
$D = [Activator]::CreateInstance($dicType )
Run Code Online (Sandbox Code Playgroud)