Problems with generics in C # in parameter

I have a class as follows:

Class foo<T> 
{
  anotherfoo<T>;

  foo(){}
  foo(foo<T> aFoo)
  { anotherfoo = aFoo; }
}
void main() 
{
foo<string> obj1 = new foo<string>();
foo<int> obj2 = new foo<int>(obj1);
}

This time I get an error: cannot convert from foo <string> to foo <int>.

But I need that in this class "foo" another obj foo of a different type, is this possible?

+3
source share
3 answers

Your class Foo<T>has a type field Foo<T>. This means that everything you select for your type Twill determine the type of field.

An alternative would be to provide a non-generic base class (or interface) as such:

public abstract class FooBase
{
}

public class Foo<T> : FooBase
{
    private FooBase _anotherFoo;
    ...
}
+12
source

Foo, .

interface IFoo {
  // add whatever you need here
}

class Foo<T>: IFoo {
  IFoo anotherfoo;

  Foo(){}
  Foo(IFoo aFoo)
  { anotherfoo = aFoo; }
}

void main() {
  Foo<string> obj1 = new Foo<string>();
  Foo<int> obj2 = new Foo<int>(obj1);
}
+4

- T IConvertible.

If you do this, you can add a method that created foo of a specific type using IConvertible.ToType to convert it directly to your type.

This will work for string and int and any other type that implemented IConvertible, but only those types.

0
source

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


All Articles