gpt4 book ai didi

c# - 如何在 C# 中编写泛型方法及其默认等效项

转载 作者:太空宇宙 更新时间:2023-11-03 21:20:13 25 4
gpt4 key购买 nike

我认为这个例子非常简单并且展示了我想要实现的目标:

public class A : A<object>
{
// public static A GetInstance() => new A();
// I can't do this, because cannot override static methods
}

public class A<T>
{
public static A<T> GetInstance() => new A<T>();

// public static A GetInstance() => new A();
// can't do this, because it says that the method is already defined
}

我基本上希望能够使用 GetInstance 方法有两种方式:

  • 指定类型 T : A<T>.GetInstance()A.GetInstance<T>() (哪个无关紧要)- 哪个应该返回类型 A<T>
  • 不指定此类型:A.GetInstance() - 它应该返回类型 A .

我怎样才能做到这一点?

最佳答案

using System;

public class Program
{
public static void Main()
{
Console.WriteLine(A.GetInstance());
Console.WriteLine(A<int>.GetInstance());
Console.WriteLine(A.GetInstance<bool>());
/*
output :
Program+A
Program+A`1[System.Int32]
Program+A`1[System.Boolean]
*/
}

//类

    public class A : A<object>
{
// non-generic method in non-generic class
public static A GetInstance()
{
return new A();
}

// generic method
public static A<T> GetInstance<T>()
{
return new A<T>();
}
}

public class A<T>
{
// non-generic method in generic class
public static A<T> GetInstance()
{
return new A<T>();
}
}
}

关于c# - 如何在 C# 中编写泛型方法及其默认等效项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31315936/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com