Inheriting C # Generics

I have the following class

public class AccountingBase<TItemType> where TItemType : AccountingItemBase

And in my AccountItemBase, I have the following property:

public virtual AccountingBase<AccountingItemBase> Parent { get; set; }

in my AccountBase, I am trying to do the following

item.Parent = this;

Logically, this should work, since TItemType inherits from AccountingItemBase, but instead I get the following error:

> Error 1 Cannot implicitly convert type
> 'TGS.MySQL.DataBaseObjects.AccountingBase<TItemType>'
> to
> 'TGS.MySQL.DataBaseObjects.AccountingBase<TGS.MySQL.DataBaseObjects.AccountingItemBase>'

How to set parent property of child properties to itself (inside parent class)

+3
source share
2 answers

No, your intuition is wrong. It should not work because generic classes are not variants in .NET.

, TItemType AccountingItemBase , AccountingBase<TItemType> AccountingBase<AccountingItemBase>. , AccountingBase<TItemType> TItemType. , , :

AccountingBase<SomeSubtype> x = new AccountingBase<SomeSubtype>();
AccountingBase<AccountingItemBase> y = x;
y.SomeField = new OtherSubtype();

, , AccountingBase<SomeSubtype>, SomeSubtype, OtherSubtype!

, .

. NDC 2010, . .NET 4 , .

, :

  • , AccountingBase. , , . Parent .
  • AccountingBase generic , ... , ...
+6

Jon :

  • IAccountingBase, , AccountingItemBase ( , , .)

  • , AccountingItemBase . , ( , ) , Child . , , , . , , , AccountReconciler , .

+1

Source: https://habr.com/ru/post/1771936/


All Articles