簡體   English   中英

將對象轉換為MyType <T> 其中T可以是任何類型

[英]Cast Object to MyType<T> where T can be any type

我有一些代碼在程序集中搜索MyType<T>類型的所有類型。 T可以是任何類型,我可以使用Activator.CreateInstance創建這些類型的對象。 我需要將這些對象傳遞到期望使用MyType<T>的方法中,因此我需要以某種方式將每個對象從Object(由Activator.CreateInstance返回)轉換為MyType<T>

您需要的是GetGenericTypeDefinition-MakeGenericType組合的組合,以形成您自己的新類型。 這是一個例子:

    public class  GenericTypeTest<T>
    {
        T value;
    }

    void MakeTest()
    {
        var newType = typeof(double);
        var customType = typeof(GenericTypeTest<object>).GetGenericTypeDefinition().MakeGenericType(newType);
        var createdObject = Activator.CreateInstance(customType);
    }

如果要使用createdObject,則有點復雜,因為您不能“硬編碼”任何東西:

    public class  GenericTypeTest<T>
    {
        public GenericTypeTest(T value)
        {
            this.value = value;
        }
        public T value {get; protected set; }
    }

    public void ShowSomething<T>(GenericTypeTest<T> genericContainer)
    {
         MessageBox.Show(genericContainer.value.ToString());
    }

    void MakeTest()
    {
        var newType = typeof(double); object newValue = 1.0;

        var customType = typeof(GenericTypeTest<object>).GetGenericTypeDefinition().MakeGenericType(newType);
        var createdObject = Activator.CreateInstance(customType, newValue);

        this.GetType().GetMethod("ShowSomething").MakeGenericMethod(newType).Invoke(this, new object[] { createdObject });
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM