请教如何反射一个带可变参数的方法?

gw_tong 2009-11-07 03:53:40
请教如何反射一个可变参数的方法?
例如:
public static class cls1{
public static void fncInvoke(params string[] sAry){
// do something
}
}
请教我如何来反射这个 cls1.fncInvoke 静态方法?
...全文
233 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
gw_tong 2009-11-07
  • 打赏
  • 举报
回复
啊呀,不好意思,是我把被调用的地方搞错了。太谢谢你了。
gw_tong 2009-11-07
  • 打赏
  • 举报
回复
我没有忽悠阿,就在那个
return mthInfo.Invoke( null, new object[] { new string[] { "Abc,s","," } } );
地方抱错了。
wartim 2009-11-07
  • 打赏
  • 举报
回复
MethordInfo.Invoke(null,new object[]{"1","2"})
gw_tong 2009-11-07
  • 打赏
  • 举报
回复
private object TestInstance( string clsName, string mthName, params object[] objArg ) {
Type typClass = null;
object objClass = null;
object objReturn = null;
Assembly[] ablAry = AppDomain.CurrentDomain.GetAssemblies();
try {
foreach ( Assembly abl in ablAry ) {
foreach ( Type t in abl.GetTypes() )
if ( t.FullName.EndsWith( clsName ) ) {
MethodInfo mthInfo = t.GetMethod( mthName );
if ( ! IsStaticClass( typClass = t ) )
objClass = abl.CreateInstance( ( typClass = t ).FullName );
int iArg = mthInfo.GetParameters().Length;
object[] objSendArg = new object[iArg];
if ( objArg != null && objArg.Length > 0 ) {
if ( objArg.Length < iArg )
throw new Exception( "调用参数的个数不够。" );
else
for ( int i = 0; i < iArg; i++ )
objSendArg[ i ] = objArg[ i ];
}
if ( mthInfo.IsStatic )
//return mthInfo.Invoke( null, ( objArg == null && mthInfo.GetParameters().Length > 0 ? new object[] { null } : new object[] { objSendArg } ) );
return mthInfo.Invoke( null, new object[] { new string[] { "Abc,s","," } } ); else
objReturn = ( mthInfo.Invoke( objClass, objSendArg ) );
throw new Exception( "反射成功。" );
}
}
} catch ( Exception ex ) {
Console.WriteLine( ex.Message );
} finally {
if ( objClass != null && typClass.GetMethod( "Dispose" ) != null )
typClass.GetMethod( "Dispose" ).Invoke( objClass, null );
}
return objReturn;
}
CsToD 2009-11-07
  • 打赏
  • 举报
回复
忽悠...

我是试过了才给你回复的....
gw_tong 2009-11-07
  • 打赏
  • 举报
回复
这个方法我试过了,报错:参数计数不匹配。
CsToD 2009-11-07
  • 打赏
  • 举报
回复
MethordInfo.Invoke(null,object[]{new string[]{"a","b"}})
gw_tong 2009-11-07
  • 打赏
  • 举报
回复
不好意思,我可能没有说明白,我想知道用MethordInfo.Invoke(null,object[])的第二个参数怎么设定?
CsToD 2009-11-07
  • 打赏
  • 举报
回复
跟普通方法没什么区别吧?

typeof(cls1).GetMethod("fncInvoke",new Type[]{typeof(string[])})

111,125

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧