使用类型C#重载方法

Mat*_*att 11 c# types overloading overload-resolution

我想知道以下是否可行.创建一个接受匿名类型(string,int,decimal,customObject等)的类,然后重载方法根据Type执行不同的操作.例

    class TestClass<T>
{
  public void GetName<string>()
  {
      //do work knowing that the type is a string    
  }

  public string GetName<int>()
  {
      //do work knowing that the type is an int

  } 

  public string GetName<int>(int addNumber)
  {
      //do work knowing that the type is an int (overloaded)    
  } 

  public string GetName<DateTime>()
  {
      //do work knowing that the type is a DateTime

  } 

  public string GetName<customObject>()
  {
      //do work knowing that the type is a customObject type    
  }

}
Run Code Online (Sandbox Code Playgroud)

所以现在我可以调用GetName方法,因为我在初始化对象时已经传入了类型,所以找到并执行了正确的方法.

TestClass foo = new TestClass<int>();

//executes the second method because that's the only one with a "int" type
foo.GetName();
Run Code Online (Sandbox Code Playgroud)

这可能还是我只是在做梦?

BFr*_*ree 12

你想要做的是这样的:

class TestClass<T>
{
   public string GetName<T>()
   {
      Type typeOfT = typeof(T);
      if(typeOfT == typeof(string))
      {
          //do string stuff
      }
   }
}
Run Code Online (Sandbox Code Playgroud)

虽然这可能的,但你有点挫败了泛型的目的.泛型的一点是当类型没有关系,所以我不认为仿制药是在这种情况下适当的.


Qwe*_*tie 5

“专业化”在 C# 中是不可能的,就像在 C++ 中一样。在 .NET 泛型中,<T> 的泛型类或方法对于 T 的所有可能值必须相同。这允许运行时对两种不同的引用类型进行优化,例如 TestClass<string> 和 TestClass<List<int >>,共享相同的机器语言代码。(不同的值类型获得单独的机器代码,但你仍然不能专门化。)

我发现创建这样的通用接口或基类有时会有所帮助:

abstract class Base<T> {
  public abstract T GetName();
  // any common code goes here that does not require specialization
}
Run Code Online (Sandbox Code Playgroud)

并在派生类中进行专业化:

class IntVersion : Base<int> {
  public override int GetName() { return 1; }
  public int GetName(int addNumber) { ... }
}
class StringVersion : Base<string> {
  public override string GetName() { return "foo"; }
}
class DateTimeVersion : Base<DateTime> {
  public override DateTime GetName() { return DateTime.Now; }
}
Run Code Online (Sandbox Code Playgroud)