ジェネリックを使用できます。新しいタイプのオブジェクトを作成すると、コード ビハインドでクラス定義が自動的に作成されます。
public class GenericClass<T>
{
public T MyProperty { get; set; }
public void TestMethod()
{
Console.WriteLine(MyProperty.ToString());
}
}
その後、別のタイプで使用できます
var myIntClass = new GenericClass<int>();
var myStringClass = new GenericClass<string>();
myIntClass.MyProperty = 1;
myStringClass.MyProperty = "test";
myIntClass.TestMethod();
myStringClass.TestMethod();
ジェネリック クラスが特定のインターフェイスを実装している、クラスである、コンストラクターを持っている必要があるように、制約を設定することもできます。パブリック インターフェイス IPrintable { void Print(); }
public class GenericClassWithConstraint<T> where T : IPrintable
{
public T MyProperty { get; set; }
void Print()
{
MyProperty.Print();
}
}
また、新しいキーワードdynamicも確認してください。実行時にオブジェクトで作業できるようになります