在泛型类C中调用类型参数的函数#

时间:2016-01-10 12:16:17

标签: c# generics inheritance

我们如何调用在通用基类中定义为抽象的函数。

我有一个通用的

class Class1<T> where T : class, new()

和多个派生自

的类
Class2: Class1<Class2> 
Class3: Class1<Class3>

泛型类有3个函数

1→接受动态对象并将所有值放入derive

对象中的相应属性

2→接受ID,查找数据库中相应的行,将动态对象传递给func1并返回结果

3→一个listall函数,它返回表

中的所有行

这是通用代码

public abstract partial class Class1<T> where T : class, new()
{
    public static EntityLayout EntityLayout { get; protected set; }

    [TypeAttributes(TypeAttributes.Options.IsPrimary, TypeAttributes.Options.IsAutoIncrement)]
    /// <summary> Automatically Incremented 64 bit Integer Primary Key
    /// represents the Unique ID of each row in Table </summary>
    public long ID { get; set; }
    /// <summary> Converts the row returned from Database to Object </summary>
    /// <param name="row"></param>
    /// <returns></returns>
    public abstract T GetDetails(dynamic row);
    public static T GetDetails(long ID)
    {
        var row = Shared.SessionWrapper.Current.globaldbcon.QuerySingle("SELECT * FROM [" 
            + EntityLayout.ContainerName + "].["
            + EntityLayout.TableName + "] WHERE ID=@0", ID);
        if (row != null) return GetDetails(row);
        return new T();
    }
    public static List<T> ListAll()
    {
        List<T> result = new List<T>();
        foreach (var row in Shared.SessionWrapper.Current.globaldbcon.Query("SELECT * FROM [" 
            + EntityLayout.ContainerName + "].["
            + EntityLayout.TableName + "]")) result.Add(GetDetails(row));
        return result;
    }
}

示例类实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Arinsys.Database;

namespace WebApplication1.Models
{
    [EntityAttributes(EntityAttributes.Options.TestingEnabled)]
    public class Class3 : Class1<Class3>
    {
        static Class3()
        {
            EntityLayout.DisplayName = "Users";
        }
        /// <summary> User ID of the User </summary>
        public long UID { get; set; }
        /// <summary> User ID of the User if defined in Universal Data Store  </summary>
        public long UDSID { get; set; }
        /// <summary> Login ID of User </summary>
        public string LoginID { get; set; }
        /// <summary> Registered email of the user. If not set will be set same as LoginID </summary>
        public string Registeredemail { get; set; }
        [TypeAttributes(TypeAttributes.Options.IsPassword)]
        /// <summary> Password of user </summary>
        public string Password { get; set; }
        /// <summary> A Unique Security Stamp used for activation/deactivation of account or similar intense tasks </summary>
        public string SecurityStamp { get; set; }
        /// <summary> Timezone ID of the Default Timezone of User </summary>
        public string DefaultTimezone { get; set; }
        /// <summary> Current Status of User </summary>
        public string CurrentStatus { get; set; }
        /// <summary> Discriminator which defines the type of user in multi-user heirarchy scenario </summary>
        public string UserType { get; set; }
        /// <summary> Number of failed login attempts in total or same session depending upon configuration. Resets after Successful Login </summary>
        public short FailedAttempts { get; set; }
        /// <summary> Date Time of Last Failed Login Attempt in UTC </summary>
        public DateTime LastFailedAttempt { get; set; }
        /// <summary> Date Time of Last Successful Login in UTC </summary>
        public DateTime LastLogin { get; set; }
        /// <summary> Creation Date of User Account in UTC </summary>
        public DateTime CreationDate { get; set; }
        public override Class3 GetDetails(dynamic row)
        {
            Class3 result = new Class3();
            if (row != null)
            {
                result.ID = Convert.ToInt64(row.ID);
                result.UID = Convert.ToInt64(row.UID);
                result.UDSID = Convert.ToInt64(row.UDSID);
                result.UserType = row.UserType;
                result.LoginID = row.LoginID;
                result.Password = row.Password;
                result.Registeredemail = row.Registeredemail;
                result.SecurityStamp = row.SecurityStamp;
                result.DefaultTimezone = row.DefaultTimezone;
                result.CurrentStatus = row.CurrentStatus;
                result.FailedAttempts = Convert.ToInt16(row.FailedAttempts);
                result.LastFailedAttempt = Convert.ToDateTime(row.LastFailedAttempt);
                result.LastLogin = Convert.ToDateTime(row.LastLogin);
                result.CreationDate = Convert.ToDateTime(row.CreationDate);
            }
            return result;
        }
    }
}

在发布前到处寻找答案已经两周了,但无法找到解决方案。

我想要的是ListAll函数应该调用1st函数。由于它定义了抽象,我确信派生类必须有一个实现(即使它可能只是抛出NotImplementException,但实现是有保证的)

我首先通过反射在泛型类本身中定义了第一个函数的实现。虽然这很有效,但它非常慢,通过在控制器动作的开始/结束时启动/停止秒表来进行性能基准测试,并且仅用了100行就花了大约35秒,所以它肯定不适合生产使用

注意事项

  • 静态无法定义为抽象
  • 无法从静态上下文访问实例成员
  • 因性能问题而无法使用反射

我认为最接近的可能解决方案(但我无法理解如何在我的情况下使用它们)

  • 将所有方法转换为实例方法并使用singleton
  • 使用接口
  • 在派生类中定义一个静态方法,并假设它将在所有类中存在,如果我这样做,那么在这种情况下如何访问T上的静态方法

我想要实现的是ListAll函数应该调用第一个接受动态对象的函数。

有些问题非常接近,但这些问题都没有解决我的问题。

Stack Overflow Q1 Stack Overflow Q2 Stack Overflow Q3

1 个答案:

答案 0 :(得分:1)

看起来设计应该像这样

public abstract partial class Class1<T> where T : Class1<T>, new()
{
    protected abstract void Load(dynamic row);

    private static T GetItem(dynamic row)
    {
        var item = new T();
        if (row != null)
            item.Load(row);
        return item;        
    }

    public static T GetDetails(long ID)
    {
        var row = Shared.SessionWrapper.Current.globaldbcon.QuerySingle("SELECT * FROM [" 
            + EntityLayout.ContainerName + "].["
            + EntityLayout.TableName + "] WHERE ID=@0", ID);
        return GetItem(row);
    }

    public static List<T> ListAll()
    {
        List<T> result = new List<T>();
        foreach (var row in Shared.SessionWrapper.Current.globaldbcon.Query("SELECT * FROM [" 
            + EntityLayout.ContainerName + "].["
            + EntityLayout.TableName + "]")) result.Add(GetItem(row));
        return result;
    }
}

和示例实现

public class Class3 : Class1<Class3>    {
{
    // ...
    protected override void Load(dynamic row)
    {
        // No need to check for null, it is enforced by the base class
        ID = Convert.ToInt64(row.ID);
        UID = Convert.ToInt64(row.UID);
        // ...
    }
}

基本上,您将探索.NET泛型类约束(T : Class1<T>)支持的Curiously recurring template pattern,以确保派生类包含抽象Load方法,而new T()部分是由new()约束强制执行。