Common objects in C #

I have a problem with litte and I need help :)

For example, I have an abstract abstract class

public abstract class BaseDefinition { public int Id { get;set; } public string Name { get;set; } } 

and another base class

 public abstract class BaseParentClass { public string Name { get;set; } public string Schema { get;set; } } 

and the first general abstract class

 public abstrac class BaseParentClass<T> : BaseParentClass where T : BaseDefinition { public IList<T> Objects {get;set;} } 

and first implementations

 public class ClassADefintion : BaseDefinition { public bool IsChanged {get;set;} } public class ClassAObject : BaseParentClass<ClassADefinition> { public bool OtherField {get;set;} } public class ClassBDefintion : BaseDefinition { public bool IsBBBChanged {get;set;} } public class ClassBObject : BaseParentClass<ClassBDefinition> { public bool OtherBBBBField {get;set;} } 

Sorry for the class name, but I can’t create anything better (this is just an example) As you can see, now everything is in order :).

I have some methods that return an IEnumerable common implementation

 IEnumerable<ClassBObject> ClassBObjectCollection; IEnumerable<ClassAObject> ClassAObjectCollection; 

Now I have to create a method that can accept shared objects in IEnumerable

 public void DoWork(IEnumerable<BaseParentClass<BaseDefinition>> objects) { foreach(var baseObj in objects) { foreach(var baseDef in baseObj.Objects) { // do some work } } } 

As I recall, BaseObject<BaseDefinition> != ClassAObject , but the compiler does not display any errors. I remember in .NET in a common interface. We can use IN and OUT T, so I'm trying to do this

 public interface IBaseParentClass<out T> where T : BaseDefinition { IList<T> Objects {get;set;} } 

Yup, you cannot list <out T> . Anyone have an idea on this issue?

I can get these field values ​​by reflection, but I have an abstract class and interface, so I think this is the best way.

+4
source share
1 answer

I don't have a compiler, but I think you can rewrite DoWork as such:

 public void DoWork<T>(IEnumerable<BaseObject<T>> objects) where T : BaseDefinition { foreach(var baseObj in objects) { foreach(var baseDef in baseObj.Objects) { // do some work } } } 

I'm not sure if the compiler can output T for you, try it.

Another possibility may be that if you still list these objects, create objects of type IEnumerable (Of T).

+2
source

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


All Articles