![](/img/trans.png)
[英]Using Activator.CreateInstance in generic class combined with “new” modifier on method
[英]Calling a method on a generic base class created with Activator.CreateInstance
以下程序可以正常工作。 但是,我想將其更改為不使用InvokeMember。 我希望能夠將CreateInstance的返回值轉換為GenericBase並直接調用Foo方法。 在此代碼示例中,我知道類型是派生的。 但是,在我的實際代碼中,我只知道類型是從GenericBase派生的。 我將對象 強制轉換為GenericBase的所有嘗試均無法編譯。 C#堅持在類型轉換中使用GenericType時提供類型參數。
這可能嗎?
using System;
using System.Collections.Generic;
using System.Text;
namespace GenericTest
{
class Program
{
static void Main(string[] args)
{
Type t = typeof(Derived);
object o = Activator.CreateInstance(t);
t.InvokeMember("Foo", System.Reflection.BindingFlags.InvokeMethod, null, o, new object[] { "Bar" });
}
}
class GenericBase<T>
{
public void Foo(string s)
{
Console.WriteLine(s);
}
}
class Derived : GenericBase<int>
{
}
}
先驗地,您對GenericBase<Bar>
和GenericBase<Baz>
之間可能存在的通用功能一無所知。 他們可能沒有共同點。 因此,在不知道父泛型類的類型的情況下,您實際上根本不了解有關該對象的任何有用信息。
現在,另一方面 ,很明顯,在這個特定示例中您要說的是GenericBase<Bar>
和GenericBase<Baz>
之間有一些共同點-它們都實現了非泛型void Foo(string s)
。 因此,為了能夠對您的對象做一些有用的事情,您需要使這種行為形式化。 將Foo
放入非通用IFoo
接口,並讓GenericBase<T>
實現該接口。 然后,您可以將對象投射到IFoo
,然后調用Foo
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.