c# - 访问通用对象参数

标签 c# asp.net asp.net-mvc generics

考虑以下片段:

public class FooRepository<T> : BaseRepository<T>
    where T : EntityBase
{
    public FooRepository(ISessionFactory sessionFactory)
        : base(sessionFactory)
    {
        this.AfterWriteOperation += (sender, local) => this.Log();
    }

    public void Log()
    {
        // I want to access T here
    }
}

我想在 Log() 函数中访问 T 但问题是我无法更改构造函数签名,例如:FooRepository(ISessionFactory sessionFactory,T 实体)。我不知道如何将它传递给 Log()

还有别的办法吗?

更新:

我想在 Log() 中访问 T 的实例。

更新 2:

好吧,抱歉弄得一团糟。我不习惯所有这些东西。我将尝试在这里澄清一些事情。所以我的仓库在Service层调用:

BarRepository.Update(entityToPersist); // Bar inherits from Foo

Update 方法中调用事件 AfterWriteOperation:

if (AfterWriteOperation != null)
    AfterWriteOperation(this, e);

对于所有这些事情,我只是放弃了一个简单的事实,即上述情况中的 e 是我的实体,因此我可以通过这种方式将它传递给 Log:

(sender, local) => this.Log(local); // I will rename local to entity

并在方法中获取它。

最佳答案

like void Log(T entity) and use it inside the method.

Well just do that :

using System;

namespace Works4Me
{
    public interface ISessionFactory { }
    public class EntityBase { }
    public class BaseRepository<T> where T : EntityBase { }

    public class FooRepository<T> : BaseRepository<T>
        where T : EntityBase
    {
        public FooRepository(ISessionFactory sessionFactory)
        {
        }

        public void Log(T entity)
        {
        }
    }

    public class Test
    {
        public static void Main()
        {
        // your code goes here
        }
    }
}

Success #stdin #stdout 0.01s 33480KB

关于您的其他声明:

I want to access the instance of T inside Log().

T 本身没有实例。您可以使用 typeof(T) 获得表示 TType 对象。

关于c# - 访问通用对象参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27269933/

相关文章:

c# - 局部 View 不刷新

asp.net-mvc - MVC C# 选择位置

c# - 用于动态解析程序集的 Unity IoC

c# - CS0019 无法将 Vector2 与 double 相乘

c# - 如何通过外部调制解调器连接的串口发送拨号信息?

asp.net - 如何在 visual studio 2012 中添加 Microsoft.ReportViewer.WebForms 8.0.0.0 的引用?

javascript - 在不涉及输入字段的情况下,在按下按钮时显示 jQueryUI 日期选择器

c# - 无法打开登录请求的数据库 "Database"

c# - 使用 OpenXML SDK 2.0 对来自 tableCell 的文本进行对齐

asp.net - 只读数据库连接字符串