Overload with a generic type parameter?

I would like to add a generic type method DoSomething<T>, but for backward compatibility I want it to simply pass the type parameter for the generic type from an existing method with the same name.

public void DoSomething<T>(Data data)
{
    //do something with Data, it depends on the type of T
}

public void DoSomething(Data data, Type dataType)
{
    DoSomething<dataType>(group);
}

However <dataType>, the new one DoSomethingproduces the following type-checking error: "Preferred type name or namespace."

Can someone help me understand the gap in my thinking that makes the above pattern an error of type checking? Is that what I'm doing ... bad design?

+3
source share
4 answers

- .

:

  • . , .

  • , . , .

:)

+15

, :

private void DoSomething<T>(Data data)
{
    DoSomething(data, typeof(T));
}

private void DoSomething(Data data, Type dataType)
{
    ...
}
+7

, . , , . Type - , . , 2 .

DoSomething .

static void DoSomething<T>(Data data) {
  DoSomething(data, typeof(T));
}

static void DoSomething(Data data, Type dataType) {
  ...
}
+6
source

If this is a private method, what is the problem for external backward compatibility?

+1
source

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


All Articles