通用类构造函数获取父项,在父项中设置值?

时间:2015-06-24 10:55:56

标签: c# generics

我正在创建一组庞大的类,其中我使用泛型类构造函数扩展了这些类的功能。

现在我想将所有特定于域的逻辑移动到这个通用构造函数中,但是当我调用“扩展”中的方法时,如何获取调用者对象时我有点困惑。当在父类中调用方法时,等于“this”它们是自己的。

另外,从扩展程序调用时,如何在父级中设置Id? long id是我希望能够从一般调用的方法更改的值。在使用DomainLogic构造函数扩展的任何类中,它总是存在。

示例:

public class TestUser : DomainLogic<TestUser>
{
    public TestUser(string Name)
    {
        this.Id = 0;
        this.Name = Name;
    }

    public long Id { get; set; }
    public string Name { get; set; }

    public override int GetHashCode()
    {
        return (int)Id;
    }
}

public class DomainLogic<T> where T : class
{
    public void Save()
    {
        //
        // Code that stores the object in repository here.
        // How do i get the calling object?
        // Repo<T>.Save(calling object)
        //
        // Otherwise i have to use:
        //
        // public void Save(T entity)
        // {
        //     if(entity.GetHashCode() == 0)
        //     { 
        //         // entity.Id = Repo<T>.Next(); // How can i set a parent value from generic called method?
        //
        //         // More logic we apply when this is considered a newly saved object.
        //     }
        //     else
        //     {
        //         // More logic we apply when this is considered a modified object.
        //     }
        //
        //     Repo<T>.Save(entity);
        // }
        //
    }
}

1 个答案:

答案 0 :(得分:1)

  

[Id属性]在使用DomainLogic构造函数扩展的任何类中始终存在

如果您希望能够从Id访问DomainLogic类,请将DomainLogic<T>.Save()属性放入。{/ p>

此外,您可以在this中使用DomainLogic<T>.Save()

相关问题