正确定义的类 [英] Correctly defined class

查看:87
本文介绍了正确定义的类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好,

我需要帮助我的defniton课程。我有类与Sql的连接。什么是更好的?所有班级都不仅仅是这门课程。感谢您的帮助

please i need help with my defniton class. I have class which connection to Sql. What is better? And no only this class for all class. Thanks for help

1。创建对象以获取方法和属性。

1. Create object to get to the methods and properties.

public class Test {
        public SqlConnection con { get; set; }

        public Test() {
                con = new SqlConnection(connetionString);
        }
}


2。组成

2. Composition

public class Test {
        public SqlConnection con { get; set; }

        public Test() {
                con = new SqlConnection(connetionString);
        }

        public void Open() {
                con.Open();
        }
}


3。我 nheritance

public class Test : SqlConnection {
        public Test() : this(connetionString) {
        }
}

谢谢

推荐答案

什么会上课吗?如果它像存储库或使用数据,则只能存储连接字符串参数。在像GetById这样的方法中,您可以创建SqlConnection实例,打开它并执行命令。

What will class do? If it is like repository or working with data you can store connection string parameter only. In method like GetById you create SqlConnection instance, open it and execute command.

这个解决方案更好,因为应该处理SqlConnection。您的示例没有实现一次性模式。

This solution is better because SqlConnection should be disposed. Your examples don't have implementation of disposable pattern.

您的示例问题是封装原则。这意味着您不应该将SqlConnection公开为public,但它应该是私有的,并且您应该封装它的方法/属性。但你为什么需要呢?

Problem of your examples is encapsulation princip. It means you should not to expose SqlConnection as public but it should be private and you shoudl encapsulate method/properties of it. But why do you need it?


这篇关于正确定义的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆