考虑以下片段:
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.
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
insideLog()
.
T
本身没有实例。您可以使用 typeof(T)
获得表示 T
的 Type
对象。
关于c# - 访问通用对象参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27269933/