The generalization routine designation and standard signature are identical.

Suppose you have a class that has methods using T. And you also have standard methods with the same name.

What happens if T is of the same type as the standard method? The standard method is called.

Is there any way to get him to name the T-method anyway?

using System;

namespace ConsoleApplication3 { class Program { static void Main() { Generics<Int32> anInt = new Generics<Int32>(4); Generics<String> aString = new Generics<String>("test"); } } public class Generics<T> { public T Member; public String ErrorMessage; public Generics(T member) { this.Member = member; } public Generics(String errorMessage) { this.ErrorMessage = errorMessage; } } } 
+8
generics c # method-overloading
source share
3 answers

Sorry no.

The simplest solution is to use two different method names to indicate the difference in behavior. Since the names of the methods in question are constructors, you have no control over the names, so you must change at least one of them to a regular method. For example:

 public class Generics<T> { public T Member; public String ErrorMessage; public Generics(T member) { this.Member = member; } private Generics() { // empty constructor just to allow the class to create itself internally } public static Generics<T> FromError(String errorMessage) { return new Generics<T> { ErrorMessage = errorMessage }; } } 

Personally, I would change both constructors to static methods, so the difference in behavior is completely understandable to the user. However, if you change only one constructor, make it a mistake.

+5
source share

Ok, I will make my comment in return.

First of all, DO NOT. NOT. You want people to be able to read your code, not just computers. (There I fulfilled my duty as a member of a C # programmer)

Secondly.

As described here :

If you create your code so that the compiler cannot determine when it compiles the type you are calling with, you can force it to use a common method.

 static Generics<T> Test<T> (T parameterToTest) { return new Generics<T>(parameterToTest); } static void Main() { Generics<Int32> anInt = Test<Int32>(4); Generics<String> aString = Test<String>("test"); } 
+1
source share

I just did this (for this particular case):

I added an empty protected constructor in Generics

  protected Generics() { } 

And then I got for a specific case T = string

  public class GenericsOfString : Generics<String> { public GenericsOfString(String text, Boolean isErrorMessage) { if (isErrorMessage) { this.ErrorMessage = text; } else { this.Member = text; } } } 
0
source share

All Articles