これをC#で実行したいのですが、方法がわかりません。
クラス名が-eg:の文字列があり、FooClass
このクラスで(静的)メソッドを呼び出したい:
FooClass.MyMethod();
明らかに、リフレクションを介してクラスへの参照を見つける必要がありますが、どうやって?
回答:
Type.GetType
メソッドを使用する必要があります。
これは非常に簡単な例です:
using System;
using System.Reflection;
class Program
{
static void Main()
{
Type t = Type.GetType("Foo");
MethodInfo method
= t.GetMethod("Bar", BindingFlags.Static | BindingFlags.Public);
method.Invoke(null, null);
}
}
class Foo
{
public static void Bar()
{
Console.WriteLine("Bar");
}
}
この方法で同じアセンブリの内部にあるタイプを見つけるのは非常に簡単なので、私は単純だと言います。あなたがそれについて何を知る必要があるかについてのより完全な説明についてはジョンの答えを見てください。タイプを取得したら、私の例ではメソッドを呼び出す方法を示します。
を使用できますがType.GetType(string)
、名前空間を含む完全なクラス名を知っている必要があります。現在のアセンブリまたはmscorlibにない場合は、代わりにアセンブリ名が必要です。(理想的には、Assembly.GetType(typeName)
代わりに使用します-アセンブリ参照を正しくするという点で、より簡単です!)
例えば:
// "I know String is in the same assembly as Int32..."
Type stringType = typeof(int).Assembly.GetType("System.String");
// "It's in the current assembly"
Type myType = Type.GetType("MyNamespace.MyType");
// "It's in System.Windows.Forms.dll..."
Type formType = Type.GetType ("System.Windows.Forms.Form, " +
"System.Windows.Forms, Version=2.0.0.0, Culture=neutral, " +
"PublicKeyToken=b77a5c561934e089");
簡単な使い方:
Type typeYouWant = Type.GetType("NamespaceOfType.TypeName, AssemblyName");
サンプル:
Type dogClass = Type.GetType("Animals.Dog, Animals");
返信に少し遅れますが、これでうまくいくはずです
Type myType = Type.GetType("AssemblyQualifiedName");
アセンブリ修飾名は次のようになります
"Boom.Bam.Class, Boom.Bam, Version=1.0.0.262, Culture=neutral, PublicKeyToken=e16dba1a3c4385bd"
使用できます
Type.GetType()
クラス名を取得し、それを使用してそのオブジェクトを作成することもできます Activator.CreateInstance(type);
using System;
using System.Reflection;
namespace MyApplication
{
class Application
{
static void Main()
{
Type type = Type.GetType("MyApplication.Action");
if (type == null)
{
throw new Exception("Type not found.");
}
var instance = Activator.CreateInstance(type);
//or
var newClass = System.Reflection.Assembly.GetAssembly(type).CreateInstance("MyApplication.Action");
}
}
public class Action
{
public string key { get; set; }
public string Value { get; set; }
}
}