如何从C#中的静态方法返回T类型

本文关键字:静态方法 返回 类型 | 更新日期: 2023-09-27 18:26:37

我想在类中使用static成员,而不想使用static方法中的<T>

public class Person : AQuaryTable
{
    public string Name { get; set; }
}
public class User : AQuaryTable
{
    public string UserName { get; set; }
}
public class AQuaryTable
{
    public static List<T> SelectAll<T>()//static this T tmp
    {
        var getType = typeof(T);
        return null;
    }
}

使用这个:

var listOfPersons1 = Person.SelectAll<Person>();//don't want use type <Person>
var listOfUsers1 = User.SelectAll<User>();//don't want use type <User>
//I want to use this code:
var listOfPersons = Person.SelectAll();//exception 
var listOfUsers = User.SelectAll();//exception 

如何从C#中的静态方法返回T类型

您可以将SelectAll作为的扩展方法

public static List<T> SelectAll<T>(this T source) where T : AQuaryTable

那么你应该可以这样称呼它:

var listOfPersons = Person.SelectAll();

注意:您需要在static类中声明SelectAll方法。

从根本上说,设计一个依赖于static方法继承的模式不是一个好主意,但如果必须的话,你可以尝试这个想法:

public class Person : QueryTable<Person>
{
    public string Name { get; set; }
}
public class User : QueryTable<User>
{
    public string UserName { get; set; }
}
public abstract class QueryTable
{
    // TODO: Write as much as you can, here.
    protected static List<T> SelectAll<T>()
    {
        // ...
    }
}
public abstract class QueryTable<T> : QueryTable
{
    public static List<T> SelectAll()
    {
        return QueryTable.SelectAll<T>();
        // Note: You could just implement this inline, here.
    }
    // TODO: Put stuff that is specific to T, here.
}

将其作为实例方法,并使基类通用:

public class AQuaryTable<T>
{
    public List<T> SelectAll()
    {
    }
}
public class User : AQuaryTable<User>
{
}