【问题标题】:Call static method from generic type从泛型类型调用静态方法
【发布时间】:2015-03-09 10:45:46
【问题描述】:

我有一个带有通用参数的静态类,声明如下:

public static partial class CMSLib<TUser> where TUser : CMSLib<TUser>.UserBase
{
    public abstract class UserBase : OrmObject<TUser>
    {
        public UInt32 Id { get; set; }
        public string Login { get; set; }
        /* etc. */
    }
}

OrmObject 声明如下:

public abstract class OrmObject<T> where T: class
{
    static OrmObject()
    {
        using (var db = Db.Open())
            db.CreateTable<T>();
    }

    public static T Single(Expression<Func<T, bool>> where) { ... }
}

当我尝试从泛型参数调用方法 Single 时:

public static partial class CMSLib<TUser> where TUser : CMSLib<TUser>.UserBase
{
    public static TUser SomeFunction()
    {
        var user = TUser.Single(...); // Here error
        ...
    }
}

我收到错误'TUser' 是一个'类型参数',在给定的上下文中无效

在这种情况下我如何调用 TUser.Single 方法(必须调用OrmObject 中的静态构造函数)?

【问题讨论】:

    标签: c# generics methods static


    【解决方案1】:

    只需拨打OrmObject&lt;TUser&gt;.Single() 而不是TUser.Single()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-14
      • 2016-11-23
      • 2015-04-25
      • 2017-03-03
      • 2010-09-16
      • 1970-01-01
      • 2011-09-17
      相关资源
      最近更新 更多