Могу ли я привести текущий экземпляр к типу Generi c в C#? - PullRequest
1 голос
/ 18 апреля 2020

Я пытаюсь присвоить текущий экземпляр класса типу Generi c (как показано в моем коде). Проблема в том, что я не уверен, как преобразовать текущий экземпляр в тип Generi c ...

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);
      }
   }
}

1 Ответ

2 голосов
/ 18 апреля 2020

Измените вашу декларацию на:

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

По сути, это говорит в C# то, что вы сказали в Engli sh как ' T1 будет типом подкласса, который наследуется из этого класса BaseCollectionForm '

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...