Casting with common types

I am sure there is a simple answer to this question that revolves around co-dispersion, but I try my best to see it!

I have a class like:

internal sealed class GenericCallbackClass<T> : SomeBaseClass where T : ICallbackMessageBase { public GenericCallbackClass(string activeId, T message) : base(activeId) { Message = message; } public T Message { get; private set; } } 

Then I instantiate a class that implements ICallbackMessageBase called Foo and instantiate a new GenericCallbackClass, passing this as an argument to T for example var myCallback = new GenericCallback<Foo>("SomeID", new Foo())

Now I want to pass this to a more general instance of GenericCallbackClass, because I will have many examples of this with Foo, Bar, etc., but everyone implements ICallbackMessageBase.

So, I want to do something like var callback = myCallback as GenericCallbackClass<ICallbackMessageBase>

I can't seem to make this actor ... Any ideas how I can get around this?

+4
source share
2 answers

Why do you even need a common <T> in this situation. Is there any other code in your GenericCallback class that uses <T> . Otherwise, you can simply rely on the implementation of the interface of each object and make sure that the interface defines any common properties or operations that you may need in your Callback class.

 public class SomeBaseClass { public SomeBaseClass (string activeId) { //Persist activeId } } public interface ICallbackMessageBase { /* implementation */ } public class Foo : ICallbackMessageBase { /* implementation */ } internal sealed class GenericCallbackClass : SomeBaseClass { public GenericCallbackClass(string activeId, ICallbackMessageBase message) : base(activeId) { Message = message; } public ICallbackMessageBase Message { get; private set; } } void Main() { var specific = new GenericCallbackClass("foo", new Foo()); } 
+5
source

Have you considered using an intermediate base class?

 internal class GenericCallbackClassBase { public GenericCallbackClassBase(ICallbackMessageBase message) { Message = message; } public ICallbackMessageBase Message { get; private set; } } 

Then you can get the general version:

 internal sealed class GenericCallbackClass<T> : GenericCallbackClassBase where T : ICallbackMessageBase { public GenericCallbackClass(T message) : base(message) { } public new T Message { get { return (T)base.Message; } } } 

This is basically a wrapper that adds type checking and automatic casting for the message property. Then you can do this:

 var g = new GenericCallbackClass<A>(a); var g2 = g as GenericCallbackClassBase; 

The g.Message property will be of type A , while the g2.Message property will be of type ICallbackMessageBase .

+1
source

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


All Articles