在 C# 中构建对象的更好方法

发布于 2024-07-09 17:19:36 字数 766 浏览 4 评论 0原文

我有一个应用程序,其对象类型继承自包含应用程序对象的大部分属性的基类。 所有对象类型都存储在数据库的一张表中。 “ClassType”列确定我将 SqlDataReader 行转换为哪种对象类型。

这是我当前的实现:

SqlDataReader dr = SqlServerHelper.ExecuteReader("MyStoreProc", MySqlParmas);

if(dr.HasRows)
{
    while(dr.Read())
    {
        switch(dr["ClassType"].ToString())
        {
            case "ClassA":
                //cast sqldatareader a ClassA object
                ClassA a = new ClassFactory.CreateClassA(object p1, object p2);
            case "ClassB":
                //cast sqldatareader a ClassB object
                ClassB b = new ClassFactory.CreateClassB(object p1, object p2);
        //it continues for all objects with app....
        }
    }
}

dr.Close()

我的问题是他们对于这种类型的处理有更好的实现吗?

I have an application with my object types that inherit from a base class that contains the majority of properties for the application objects. All the object types are stored in one table in the database. The "ClassType" column determines what object type I cast the SqlDataReader row to.

Here is my current implementation:

SqlDataReader dr = SqlServerHelper.ExecuteReader("MyStoreProc", MySqlParmas);

if(dr.HasRows)
{
    while(dr.Read())
    {
        switch(dr["ClassType"].ToString())
        {
            case "ClassA":
                //cast sqldatareader a ClassA object
                ClassA a = new ClassFactory.CreateClassA(object p1, object p2);
            case "ClassB":
                //cast sqldatareader a ClassB object
                ClassB b = new ClassFactory.CreateClassB(object p1, object p2);
        //it continues for all objects with app....
        }
    }
}

dr.Close()

My question is is their a better implementation for this type of processing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

林空鹿饮溪 2024-07-16 17:19:36

如果您不想切换到代码生成 ORM,则可以使用此方法。

在对象表中,包含对象的完全限定类型名称。

然后,您可以执行以下操作:

    private Dictionary<String, Type> _objectTypes = new Dictionary<String, Type>();

    public ObjectFactory()
    {
        // Preload the Object Types into a dictionary so we can look them up later
        foreach (Type type in typeof(ObjectFactory).Assembly.GetTypes())
        {
            if (type.IsSubclassOf(typeof(BaseEntity)))
            {
                _objectTypes[type.Name.ToLower()] = type;
            }
        }
    }

现在,在全部预加载映射器的情况下,您可以将代码替换为:

    string objectName = dr["ClassType"].ToString().ToLower();
    Type objectType;

    if (_objectTypes.TryGetValue(objectName, out objectType))
    {
       return (BaseEntity)Activator.CreateInstance(objectType,reader);
    }        

将读取器传递给对象的构造函数,以便它可以完全填充自身,该类型的代码不属于工厂。

This approach is if you don't want to switch to a code generating ORM.

In your table of objects, include the fully qualified type name of the object.

Then, in you can do something like:

    private Dictionary<String, Type> _objectTypes = new Dictionary<String, Type>();

    public ObjectFactory()
    {
        // Preload the Object Types into a dictionary so we can look them up later
        foreach (Type type in typeof(ObjectFactory).Assembly.GetTypes())
        {
            if (type.IsSubclassOf(typeof(BaseEntity)))
            {
                _objectTypes[type.Name.ToLower()] = type;
            }
        }
    }

Now, with a mapper all preloaded, you can replace your code with:

    string objectName = dr["ClassType"].ToString().ToLower();
    Type objectType;

    if (_objectTypes.TryGetValue(objectName, out objectType))
    {
       return (BaseEntity)Activator.CreateInstance(objectType,reader);
    }        

Pass the reader to the constructor of your object, so it can fully populate itself, that type of code doesn't belong in the factory.

秋意浓 2024-07-16 17:19:36

我想我会倾向于使用对象关系映射器来实现这一点。 NHibernate 是 .NET 平台现有的、免费的、成熟的 ORM 解决方案的一个示例。

I guess I would lean towards an Object-Relational Mapper for this. NHibernate is an example of an existing, free, mature ORM solution for the .NET platform.

小…红帽 2024-07-16 17:19:36

感谢您的所有反馈,但我不想实施第三方工具或新语言,因为我现在没有时间学习它。

@Jonathan Hollard:

我的对象模块当前设计如下:

public class BaseClass
{
    public BaseClass() { }

    public object p1 { get; set;}

    public object p2 { get; set; }

    public virtual void ImplementLogic()  
    {
        //do some fun stuff....
    }
}

public class ClassA : BaseClass
{
    public ClassA { }

    public override void ImplementLogic()
    {
        //make it rain.....
    }
} 

public class ClassB : BaseClass
{
    public ClassB { }    

    public override void ImplementLogic()
    {
        //do some more fun stuff
    }
}

它将如何与该模型一起工作?

我是否会将第一个代码示例放入 BaseClassFactory 构造函数中,因为它会识别从 BaseClass 继承的所有类?

Thanks for all the feedback, but I do not want to implement a third party tool or new language because I do not have time right now to learn it right now.

@Jonathan Hollard:

My object module is current designed like this:

public class BaseClass
{
    public BaseClass() { }

    public object p1 { get; set;}

    public object p2 { get; set; }

    public virtual void ImplementLogic()  
    {
        //do some fun stuff....
    }
}

public class ClassA : BaseClass
{
    public ClassA { }

    public override void ImplementLogic()
    {
        //make it rain.....
    }
} 

public class ClassB : BaseClass
{
    public ClassB { }    

    public override void ImplementLogic()
    {
        //do some more fun stuff
    }
}

How would it work with this model?

Would I throw the first code sample in my BaseClassFactory constructor, because it would recognize all the classes that inherited from BaseClass?

骄兵必败 2024-07-16 17:19:36

您可以将完全限定的类型名称存储在数据库中,然后使用 Activator.GetInstance 构造它。 这将摆脱丑陋的 switch 语句,但会调用类型的构造函数而不是工厂方法。 这会达到你想要的效果吗?

You could store the fully-qualified type name in your database, and then construct it with Activator.GetInstance. This would get rid of the ugly switch statement, but would call the type's constructor instead of a factory method. Will that do what you want?

勿挽旧人 2024-07-16 17:19:36

LINQ to SQL 可能是一个合法的选择。 但是,它不能很好地处理未受主键和外键约束的数据库。 它将根据表生成类。

LINQ to SQL might be a legitimate option. However, It does not play very well with databases that are not properly constrained with Primary and Foreign keys. It will generate the class based on the tables.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文