Embedding a non-generic type into a generic

I have this class:

class Foo { public string Name { get; set; } } 

And this class

 class Foo<T> : Foo { public T Data { get; set; } } 

Here is what I want to do:

 public Foo<T> GetSome() { Foo foo = GetFoo(); Foo<T> foot = (Foo<T>)foo; foot.Data = GetData<T>(); return foot; } 

What is the easiest way to convert Foo to Foo <T>? I cannot directly use InvalidCastException), and I do not want to copy each property manually (in my actual use case, there is more than one property) if I do not need it. Is custom type conversion capable?

+4
source share
3 answers

You can create an explicit conversion from Foo within Foo<T> .

 class Program { static void Main() { Foo foo = new Foo(); foo.Name = "Blah"; Foo<int> newfoo = (Foo<int>)foo; Console.WriteLine(newfoo.Name); Console.Read(); } } class Foo { public string Name { get; set; } public object Data { get; set; } } class Foo<T> { public string Name { get; set; } public T Data { get; set; } public static explicit operator Foo<T>(Foo foo) { Foo<T> newfoo = new Foo<T>(); newfoo.Name = foo.Name; return newfoo; } } 

Edit: This only works without inheritance. It looks like you cannot perform custom conversion from the base to a derived class. See Comments from Mads Torgersen here http://social.msdn.microsoft.com/forums/en-US/csharplanguage/thread/14cf27cf-b185-43d6-90db-734d2ca3c8d4/ :

We took the liberty to predetermine conversions (throws) between base classes and derived classes and to make semantics predictable language, we do not allow you to mess with it.

It looks like you might come across a definition of a method for turning Foo into Foo<T> . This, or discard inheritance. None of the solutions seem particularly ideal.

+2
source

If you get an InvalidCastException , the type of Foo returned by GetFoo() is not Foo<T> . You need to either pass T or typeof(T) to this function so that it can return an instance of Foo<T> .

+1
source

Use copy constructors. Foo implements:

 class Foo { Foo(Foo copy) { ... } } 

whereas Foo will be built using the following:

 class Bar<T> : Foo { Bar(Foo copy) : base(copy) { ... } } 

... Yes. You need to copy member by member, and this should be done in the "copy constructor".

0
source

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


All Articles