在另一个类(嵌套)C#中创建和初始化一个类

时间:2016-04-25 18:48:07

标签: c# class nested

我是C#的新手,我需要一些帮助才能在我的“Hello World”项目中使用嵌套类。

我正在尝试使用 class1.subclass1.function(args ...)创建一个可调用的类(以创建相关函数组),并且我已经做了一些有效的但是我认为这不是最佳方式。

我的代码需要在主类和嵌套类(db句柄)之间共享一个变量,并且我在类初始化时使用和参数来完成它。

namespace SameAsPrincipal
{
    public class class1
    {
        public SQLiteConnection handle = null;
        public _subclass1 subclass = null;

        public class1(string db_file)
        {
            handle = new SQLiteConnection(db_file);
            subclass1 = new _subclass1(handle);
        }

        public _subclass1
        {
            private SQLiteConnection handle = null;

            public _subclass1(SQLiteConnection handle)
            {
                this.handle = handle;
            }

            public void function(args...)
            {
                //Do something here
            }
        }
    }
}

有人知道更好的方法来创建嵌套类并在main和嵌套之间共享对象吗?

谢谢!

4 个答案:

答案 0 :(得分:1)

不是嵌套对象,而是创建两个类(在相同的范围内)并使用另一个类,例如:

background: url(img2x.jpg) 0% 0%/100%;

答案 1 :(得分:1)

如果没有关于具体应用程序的更多背景信息,很难判断它是否合适。我同意之前的答案,即分开课程通常更为正确。你的B类仍然可以在它的构造函数中使用DB句柄引用,而A类甚至可以将它传递给它。没关系。并不是因为他们共享变量,因为他们都有对同一个DB句柄的引用。

我唯一一次见过子/内部类并且不认为奇怪的是像父类中曾经使用过的简单数据对象(尽管它们可能在外部引用)。例如,如果我创建了一个链表类,我可以选择让节点类成为内部类。对于仅分组功能,常规类应该这样做。

命名空间也可用于进一步分组。例如,也许我的所有文本操作都在“MyApp.Text”命名空间中,但随后它们被进一步分组为“NumberUtils”,“NameUtils”和“ZipUtils”等类。

答案 2 :(得分:1)

在HelloWorld项目中使用嵌套类?不是一个好兆头!!

我建议不要使用嵌套类型 除非 你知道自己在做什么,并且在被问到时你有很好的解释。另请注意.NET Framework指南中明确建议不要创建public嵌套类的建议。

对于面向对象编程中的数据共享,我们有inheritance功能,这是基于关系/关联跨类共享数据/成员访问的最佳方式。

  

创建相关功能组

正如@Nex Terren建议的那样(稍作修改),你可以做类似这样的事情,这里你的Principle类将作为Factory工作,不同的类将通过它们的实例提供相关函数的聚合

public class PrincipleClass
{
  public ClassB InstanceOfClassB { get; private set; }
  public ClassA InstanceOfClassA { get; private set; }

  public PrincipleClass(string db_file)
  {
    InstanceOfClassA = new ClassA(new SQLiteConnection(db_file));
    InstanceOfClassB = new ClassB();
  }
  //More code here
}

public class ClassA
{
  public ClassA(SQLiteConnection handle)
  {
     // your code here
  }
  public void FunctionOfA1() { }
  public void FunctionOfA2() { }
}

public class ClassB
{
  public void FunctionOfB1() { }
  public void FunctionOfB2() { }
}

现在你将把你的功能组合在一起,如

new PrincipleClass.InstanceOfClassA.FunctionOfA1();
new PrincipleClass.InstanceOfClassB.FunctionOfB1();

注意 - 这可能也不是最佳解决方案,但这比使用嵌套类型更好。

答案 3 :(得分:1)

我不清楚你为什么要在这个实例中使用嵌套类。你编写它的方式,子类就是你所需要的。如果你想要多种方法(或者你称之为“函数”),只需添加你的方法。

您是否希望在此处使用嵌套类?作为一般规则,很少需要嵌套类。

namespace SameAsPrincipal
{
  public class Class1
  {
    private SQLiteConnection handle;

    public Class1(string db_file)
    {
      handle = new SQLiteConnection(db_file);
    }

    public int AddRecord(Record record)
    {
      // use handle to add record and get record Id
      return record.Id;
    }

    public void DeleteRecord(int id)
    {
      // Use handle to delete record
    }
  }
}

实例化对象时,将传入db_file,并创建连接对象。然后,每个方法都可以在调用它们时使用该连接对象。但是,通常最好在调用每个方法时为每个方法创建连接,并在操作完成后立即处理连接。当然,这取决于您的运营以及它们是否具有跨国性。在大多数情况下,使用“using”块来实例化连接是使用连接对象的好方法。您越早释放连接,机器将越早重用该连接,您可以查找连接池以了解更多信息。

以下是使用“using”使用存储过程添加人员的示例方法:

public int AddPerson(Person person)
{
  using (var connection = new SQLiteConnection(dbFile))
  {
    connection.Open();
    using (var command = new SQLiteCommand("spAddPerson",connection))
    {
      command.CommandType = CommandType.StoredProcedure;

      var idParameter = new SQLiteParameter("@Id", DbType.Int32);
      idParameter.Direction = ParameterDirection.Output;
      command.Parameters.Add(idParameter);

      command.Parameters.AddWithValue("@FirstName", person.FirstName);
      command.Parameters.AddWithValue("@LirstName", person.LastName);

      command.ExecuteNonQuery();
    }
  }

  return person.Id;
}

修改:关于您的评论

一些事情:

  1. 使用名称空间而不是父类来对类进行分组。
  2. 您应该将所有数据库方法添加到数据库类中,并创建用于为对象建模的类,而不是子类。
  3. 每个班级都应该在自己的文件中
  4. 命名空间部分是.. [] * I.E. Music类具有名称空间YourApplication.YourProject.Models - 在YourProject项目中,在名为Music的第一级文件夹中,您将找到名为Music.cs的文件,在该文件中您将找到您的音乐类。这不是一个要求,编译器不关心那样的结构。当您开始开发更多代码时,它只会让您的生活更轻松。
  5. 这是我所说的代码结构的一个例子(请记住这些部分中的每一部分都是它自己的文件)

    在项目的根目录中创建一个名为Models的文件夹。在此Models文件夹中,创建一个名为Music.cs

    的文件
    namespace YourApplication.YourProject.Models
    {
      public class Music
      {
        public int Id { get; set; }
        public string Title { get; set; }
        public double Length { get; set; }
        public string Artist { get; set; }
        public string Album { get; set; }
      }
    }
    

    在同一个(Models)文件夹中创建一个名为Film.cs的文件

    namespace YourApplication.YourProject.Models
    {
      public class Film
      {
        public int Id { get; set; }
        public string Title { get; set; }
        public double Length { get; set; }
        public string Director { get; set; }
        public string[] Actors { get; set; }
      }
    }
    

    现在回到项目根目录(不再在Models文件夹中)创建一个名为Persistence的新文件夹。

    using System;
    using System.Collections.Generic;
    using System.Data.SQLite;
    using YourApplication.YourProject.Models;
    
    namespace YourApplication.YourProject.Persistence
    {
      public static class DatabaseActions
      {
        public static string dbFile;
    
        public static Music[] ListMusic()
        {
          var musicList = new List<Music>();
    
          // database call to get all music
          using (var connection = new SQLiteConnection(dbFile))
          {
            connection.Open();
            using (var command = new SQLiteCommand("spGetMusic", connection))
            {
              var reader = command.ExecuteReader();
    
              // The try finally blocks are not strictly needed as these will are suppose to be called upon disposal
              try
              {
                // loop through records creating music objects
                while (reader.Read())
                {
                  var music = new Music();
                  music.Id = reader.GetInt32(0);
                  music.Title = reader.GetString(1);
                  musicList.Add(music);
                }
              }
              finally
              {
                reader.Close();
                connection.Close();
              }
            }
          }
          return musicList.ToArray();
        }
    
        public static int SaveMusic(Music music)
        {
          if (music.Id == 0)
          {
            // database stuff - getting the newly created database id  
          }
          else
          {
            // database calls to update record
          }
    
          return music.Id;
        }
    
        public static int SaveFilm(Film film)
        {
          if (film.Id == 0)
          {
            // database stuff - getting the newly created database id  
          }
          else
          {
            // database calls to update record
          }
    
          return film.Id;
        }
    
    
        public static Music GetMusic(int id)
        {
          var music = new Music();
    
          // database call and setting of values on music
    
          return music;
        }
    
    
        public static Film GetFilm(int id)
        {
          var film = new Film();
    
          // database call and setting of values on music
    
          return film;
        }
    
      }
    }
    

    现在最终在根上创建一个名为WorkHarness.cs的文件

    using System;
    using YourApplication.YourProject.Persistence;
    
    
    namespace YourApplication.YourProject
    {
      public class WorkHarness
      {
    
        public void Initialize()
        {
          DatabaseActions.dbFile = "your db file";
        }
    
        public void ShowMusicList()
        {
          // list the id and title so user can select by Id
          foreach (var music in DatabaseActions.ListMusic())
          {
            Console.WriteLine("{0,-10}{1}",music.Id,music.Title);
          }
        }
    
        public void DisplayMusicItem(int id)
        {
          var music = DatabaseActions.GetMusic(id);
    
          Console.WriteLine("Title: " + music.Title);
          Console.WriteLine("Length: " + music.Length);
          Console.WriteLine("Artist: " + music.Artist);
          Console.WriteLine("Album: " + music.Album);
        }
      }
    }