如果它只是一个静态类,则不需要未初始化的对象。一旦你得到的类型,例如
Type t = asm.GetType("NAMESPACE.CLASS");
你可以得到你需要
MethodInfo method = t.GetMethod("MethodName");
//getmethod has some useful overloads
//also GetMethods() returns a MethodInfo[] array containing all methods
,那么你可以调用
object result = method.Invoke(null, new object[] { param1, param2, ... });
有这样做,以及其他的方式方法。您可以使用委托来获取指向该方法的函数指针,而不是调用invoke。
我不确定如何做事件处理程序,虽然我确定如果您在Type对象下浏览intellisense,您应该能够找到某些东西。就属性而言,通常只使用它们作为对象,但如果要使用静态类的属性,并且事先已知道返回类型,则可以创建一个类来处理它:
public class ExternalProperty<PropertyType>
{
delegate PropertyType GetFunction();
delegate void SetFunction(PropertyType value);
GetFunction GetValue;
SetFunction SetValue;
public ExternalProperty(PropertyInfo externalProperty)
{
MethodInfo getMethod = externalProperty.GetGetMethod();
GetFunction getter = (GetFunction)Delegate.CreateDelegate(typeof(GetFunction), getMethod);
MethodInfo setMethod = externalProperty.GetSetMethod();
SetFunction setter = (SetFunction)Delegate.CreateDelegate(typeof(SetFunction), setMethod);
}
public PropertyType Value
{
get { return GetValue(); }
set
{
SetValue(value);
}
}
}
如果你已经知道属性类型,使用这个类很容易。假设你有一个字符串类型的属性名称:
ExternalProperty<string> PropName = new ExternalProperty(t.GetProperty("Name"));
string oldName = PropName.Value; //this will call the property's getter
PropName.Value = "new name"; //this will call the property's setter
它没有错误检查,但这样,如果你尝试通过比指定,或一个不同类型的属性,无法找到它,它会打破。这也不适用于对象,只适用于静态类。希望有所帮助。
第4步有一个错字:应该是'ilasm ThirdParty.il/dll /key=MyKey.snk'谢谢你的回答:) –
@John:谢谢,纠正。 – adrianbanks