Javaから以下のコードを使用してメソッドを呼び出しました。メソッドがあるクラスのインスタンスを渡してから実行します。C#でメソッドを呼び出す方法
Context context; //Assuming the passed Instance is initialized here
Class c = Class.forName(context.getClass().getName()); //Get the class name including it's package and initialized here
Method m = c.getMethod("thisMethod", String.class, String.class); //Initialize the Method name and it's parameter type
Object t = c.newInstance();
m.invoke(t,"data1", "data2"); //Invoke the method with 2 string
私は上記のコードをC#で変換したいと思います。私は検索しようとしましたが、このlinkが見つかりました。私が渡したインスタンスをどのように使用することができますか、私は混乱しています。これまで私はC#で以下のコードを持っています。 InvokerClass
から
class Program{
static InvokerClass ic;
private static Program programInstance = new Program();
static void Main(string[] args){
ic = new InvokerClass(programInstance);
ic.StartInvokeExample("Hello","World!");
}
//Call this method later
public static void thisMethod(String data1, String data2) {
Console.WriteLine("DATA1=>" + data1 + ", DATA2=>"+data2);
}
}
class InvokerClass{
private Object objInstance;
public InvokerClass(Object obj){
this.objInstance = obj; //Get the passed Instance and use this to determine the Class Name
}
//Do invoking here
public void StartInvokeExample(String data1, String data2){
Type t = Type.GetType("? ? ?"); //I wanted to use the `objInstance` to determine the Class name
ConstructorInfo cons = t.GetConstructor(Type.EmptyTypes);
object classObject = cons.Invoke(new object[] { });
MethodInfo m = t.GetMethod("thisMethod");
m.Invoke(classObject, new object[] { data1, data2 });
}
}
私はクラス名を初期化するためにobjInstance
を使用したいと思いますが、私は方法がわかりません。そして今のところ、私はそれが正しい方法でやっているのかどうかわかりません。
タイプt = Type.GetType( "???");をタイプt = objInstance.GetType()に置き換えます。 'objInstance'がヌルであることに気をつけてください –
代わりにコンストラクタを自分で探しているならば、' Activator.CreateInstance(myType) 'を使って型のインスタンスを作ることができます。 – HimBromBeere
'if(objInstance!= null){//ここで呼び出しを実行}'を使用することは信頼できると思いますか? @lopi確かに、 – lopi