1

私はこのシナリオを持っています: 次のようないくつかのプロパティを持つ 1 つのカスタム クラス (Customer):

public class Customer
{
    public int Handler { get; set; }
    public string Name { get; set; }
}

次のように、メソッドを持つ 1 つのカスタム クラス:

public class CustomerMethods
{
    public static void Insert(Customer customer)
    {
        //Do Something...
    }
}

そこで、クラス名、プロパティ名、プロパティ値などの情報を含むテキスト ファイルを読み込みます。しかし、実際の問題は、CustomerMethods クラスから Insert メソッドを呼び出し、Handler および Name プロパティの値を設定した後、Customer クラスをパラメータとして渡すにはどうすればよいかということです。

ああ、100以上のクラスがあるので、条件を避けようとしているのをほとんど忘れています。/o\ 皆様、さらに詳しい情報が必要な場合は、教えてください...

4

2 に答える 2

2
typeof(CustomerMethods).GetMethod(SomeName).Invoke(null, new Customer(...))

ただし、可能であれば、設計のリファクタリングを試みて、これを回避する必要があります。

于 2012-01-31T17:59:20.010 に答える
1

これらの文字列のみを使用して、静的 Insert メソッドを呼び出しましたWindowsFormsApplication1.Form1+CustomerMethods     WindowsFormsApplication1.Form1+Customer     Insert

Type customerMethodsType = Type.GetType("WindowsFormsApplication1.Form1+CustomerMethods");
Type customerType = Type.GetType("WindowsFormsApplication1.Form1+Customer");
object customerObject =  Activator.CreateInstance(customerType);

customerType.GetProperty("Handler").SetValue(customerObject, 3, null);

customerMethodsType.InvokeMember(
    "Insert",
    BindingFlags.Public | BindingFlags.InvokeMethod| BindingFlags.Static,
    null,
    null,
    new object[] { customerObject }
    );
于 2012-01-31T18:18:01.157 に答える