【问题标题】:How to capture value OOPS & Generic [closed]如何捕获价值 OOPS 和通用 [关闭]
【发布时间】:2014-09-26 16:07:44
【问题描述】:

这是我的代码。

 class Program
    {
        static void Main(string[] args)
        {
            var _User = new User { Name="Test", Age=12 };
            _User.Save();
        }
    }

    public class DBObject<T>
    {
        public void Save()
        {

        }
    }

    public class User : DBObject<User>
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

我想从保存方法中获取用户名和年龄?我怎么能这样做......请指导。谢谢

【问题讨论】:

  • 请说得具体一点。
  • 您想在User 中实现自己的Save() 还是从DBObject 访问Save()(在这种情况下,我认为您当前的代码没有问题)
  • 我想在我的数据库相关类 DBObject 中编写保存逻辑并允许其他类扩展 DBObject,但是当其他类调用 save() 函数时,实例值将传递给 DBObject 的 save() 函数.所以请指导我如何做到这一点

标签: c# oop generics


【解决方案1】:

查看您的代码时,为什么要在泛型方法中读取特定于类的属性?

我看到的唯一解决方案是使用反射,或者创建一个具有之前保存方法的抽象基类,并在 de Save() 方法中调用该方法。将泛型类型约束添加到定义 T 是基本类型的 DBObject 类。通过这种方式,您可以将特定于类的功能添加到泛型方法中。像这样的:

public abstract class Base
{
     public virtual void BeforeSave()
     {

     }

}

public class User : Base
{
     public string Name { get; set; }
     public int Age { get; set; }      

     public override void BeforeSave()
     {
          // You can access your properties here
          if (this.Name.Trim() == "")
              throw new Exception("Name is mandatory!")
     }

}

public class DBObject<T>
    where T: Base
{
    public void Save()
    {
        T.BeforeSave();
    }
}

【讨论】:

  • 无论你说什么,请写一个代码,可以帮助我想象你在说什么......谢谢
  • 只要去这个网址,告诉我他们在做什么dbentry.codeplex.com
  • 编辑了我的答案。为什么要读出这些属性?出于验证目的?
  • 我想在 Save() 函数级别捕获这些值,因为我想编写一个将数据保存到数据库的例程。所以请指导我如何从 DBObject 的保存功能中获取用户名和年龄??
  • 好吧,看看 Entity Framework.. 它为您完成了所有这些..
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-09-27
  • 1970-01-01
  • 2021-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多