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

时间:2014-10-15 10:00:04

标签: c# static

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

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 

3 个答案:

答案 0 :(得分:3)

您可以将SelectAll作为扩展方法

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

然后你应该可以这样称呼它:

var listOfPersons = Person.SelectAll();

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

答案 1 :(得分:0)

使其成为实例方法并使基类通用:

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

public class User : AQuaryTable<User>
{

}

答案 2 :(得分:0)

从根本上说,设计依赖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.
}