-3

以下に示すような名前空間があります。

 namespace testnamespace
    {
        public class testclass : System.Web.UI.Page
        {
            public static string testData;


            public void test()
            {
                string s = "fgdfgdg";

            }
            protected string Invoke(string methodname)
            {
                //string methodName = "test";
                string classname = methodname.Split('-')[0];
                 string funcname=methodname.Split('-')[1];
                 Type type = Type.GetType(classname); 
                Activator.CreateInstance(type);
                 MethodInfo method = type.GetMethod(funcname);

             string result = (string)method.Invoke(Activator.CreateInstance(type), null);
             return result;
            }
            public static string testfunc(string temp)
            {
                hdnData = temp;           
               string strval=  Invoke(s);
               return strval;

            }
        }
    }

以下に示すように、別のアプリケーションでこの dll を参照しています。

using testnamespace;
 protected void Button1_Click(object sender, EventArgs e)
        {
           string test='testfunction';
            string s=testfunc(test);
        }

関数を public im として宣言すると、エラーが発生します

"非静的フィールド、メソッド、またはプロパティにはオブジェクト参照が必要です"

しかし、パブリック静的として宣言すると、関数だけでなく他のすべての関数にもアクセスできます。変数は静的として宣言する必要があります。そのクラスのすべての関数を静的にするのではなく、関数 testfunc だけにしたいのです。これどうやってするの?

4

1 に答える 1

2

静的関数を呼び出すには、最初にクラス名を指定する必要があります。そうしないと、コンパイラはどのメソッドを呼び出すべきかわかりません。あなたの例では、次を置き換えます:

string s=testfunc(test);

string s = testclass.testfunc(test);

また、 を呼び出すときに、メソッドのシグネチャと一致する有効なパラメータを提供する必要がありますmethod.Invoke(...)。そうしないと、実行時例外が発生します。

そして、なぜそのようなデザインを作成するのかはわかりませんが(テストクラスの背後にあるアイデアも説明していません)、これは「悪い」デザインのように見えます。

于 2013-05-14T06:02:40.023 に答える