简体   繁体   English

我可以将当前实例转换为 C# 中的通用类型吗?

[英]Can I cast the current instance to a Generic Type in C#?

I am trying to assign the current instance of a class to a Generic Type (as shown in my code).我正在尝试将 class 的当前实例分配给通用类型(如我的代码所示)。 The issue is that I'm not sure how to cast the current instance into the Generic type...问题是我不确定如何将当前实例转换为通用类型......

namespace Sample
{
   public partial class BaseCollectionForm<T1, T2> : BaseForm
   {
      private static T1 instance = default(T1);

      public static T1 GetInstance()
      {
         if (instance == null)
         {
            if (System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Designtime)
            {
               MessageBox.Show("Instance does not exist.");
            }
            else
            {
               instance = (T1)Activator.CreateInstance(typeof(T1));
            }
         }

         return instance;
      }

      protected BaseCollectionForm()
      {
         InitializeComponent();

         if (System.ComponentModel.LicenseManager.UsageMode != System.ComponentModel.LicenseUsageMode.Designtime)
         {
            if (instance != null)
            {
               MessageBox.Show("Instance already exists");
            }
         }

         // This is the problem area... T1 will be the type of the SubClass that Inherits from this BaseCollectionForm class.
         // I need to assign the instance variable with this, but the this value of the subclass.
         instance = (T1)(this);
      }
   }
}

Change your declaration to:将您的声明更改为:

public partial class BaseCollectionForm<T1, T2> : BaseForm where T1 : BaseCollectionForm<T1, T2>

Essentially, this says in C# what you've said in English as ' T1 will be the type of the SubClass that Inherits from this BaseCollectionForm class '本质上,这在 C# 中说明了您在英语中所说的“ T1 将是继承自此 BaseCollectionForm class 的子类的类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM