【问题标题】:Is the usage of partial classes a good practice/design?部分类的使用是一个好的实践/设计吗?
【发布时间】:2019-10-22 14:51:46
【问题描述】:

您能说将类拆分为部分类是封装代码的一种方式吗?

另外,为什么将代码拆分为部分类不是设计模式的一部分?我的意思是你通过拆分代码来设计代码以获得更好的概览,对吗?

General.cs:

/*  SINGLETON DESIGN PATTERN (slides and https://sourcemaking.com/design_patterns/singleton)

     * INTENT
       - Ensure a class has only one instance, and provide a global point of access to it.
       - Encapsulated "just-in-time initialization" or "initialization on first use".

      * ABOUT
       - Make the class of the single instance object responsible for creation, initialization,
       access, and enforcement.

 */
namespace SpaceTaxi_3.States.GameRunning.Parser {
    public partial class LevelParser {

        private static LevelParser instance;

        public static LevelParser GetInstance() {
            return LevelParser.instance ?? (LevelParser.instance = new LevelParser());
        }

        public Dictionary<char, string> Obstacles;
        public Dictionary<char, string> Platforms;
        public Dictionary<char, string> Exits;
        public Dictionary<string, Tuple<int, char, string, int, int, Entity>> Costumer;
        public List<Entity> ObstacleEntities { get; set; }
        public List<Platform> PlatformEntities { get; set; }
        public List<Entity> ExitEntities { get; set; }

        public string[] LevelFile;

        // Wrapper
        public void Load(string fileName) {

            // Catches incorrect files here
            if (ValidMapCheck(fileName)) {
                PlatformEntities = new List<Platform>();
                ExitEntities = new List<Entity>();
                ObstacleEntities = new List<Entity>();

                Platforms = new Dictionary<char, string>();
                Exits = new Dictionary<char, string>();
                Obstacles = new Dictionary<char, string>();
                Costumer = new Dictionary<string, Tuple<int, char, string, int, int, Entity>>();

                LevelFile = ReadFile("Levels", fileName);

                Platforms = GetPlatforms(LevelFile);
                Exits = GetExits(LevelFile);
                Obstacles = GetObstacles(LevelFile);
                Costumer = GetCustomerInfo(LevelFile);

                AddEntities(GetAllTiles(LevelFile));
            }
        }

        /// <summary>
        ///  Checks whether a file exists or not
        /// </summary>
        private void ValidatePath(string file) {
            if (!File.Exists(file)) {
                throw new FileNotFoundException($"Error: " +
                                                $"The path to \"{file}\" does not exist.");
            }
        }

        /// <summary>
        ///  Finds full path to directory (e.g. directoryName: "Levels" or "Assets")
        ///  Starts from /bin/Debug folder, then goes to parent /bin, and so on.
        ///  Casts an exception if we iterated down to the root of the tree.
        /// </summary>
        private string GetPath(string directoryName) {
            DirectoryInfo dir = new DirectoryInfo(Path.GetDirectoryName(System.Reflection.Assembly.
                GetExecutingAssembly().Location));

            while (dir.Name != directoryName) {
                if (dir.FullName == dir.Root.Name) {
                    throw new FileNotFoundException(
                        $"Error: Directory \"{directoryName}\" does not exist.");
                } else {
                    foreach (var i in dir.GetDirectories()) {
                        if (i.Name == directoryName) {
                            return i.FullName;
                        }
                    }

                    dir = dir.Parent;
                }
            }
            return dir.FullName;
        }

        /// <summary>
        /// Making sure our mapfiles are not tampered with by calculating the checksum
        /// Source: https://stackoverflow.com/questions/10520048/calculate-md5-checksum-for-a-file
        /// Source: https://en.wikipedia.org/wiki/MD5
        /// </summary>
        /// <param name="filename"></param>
        public string CheckMD5(string filename)
        {
            // "using": automatically disposes the object after use,
            //  even if exception is casted
            using (var md5 = MD5.Create())
            {
                using (var stream = File.OpenRead(filename))
                {
                    var hash = md5.ComputeHash(stream);
                    return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
                }
            }
        }

        /// <summary>
        ///  Checks for invalid files and invalid filecontent
        /// </summary>
        public bool ValidMapCheck(string filename) {

            var hash = "";
            var hash32bit = "";
            Console.WriteLine("Hash: " + CheckMD5(Path.Combine(GetPath("Levels"), filename)));

            // Checks for invalid files
            if (filename != "the-beach.txt" && filename != "short-n-sweet.txt") {
                throw new ArgumentException($"Parser cannot load: {filename}");
            }

            // Checks for invalid file content
            if (filename == "the-beach.txt") {
                hash = "81b89b1908e3b3b7fcd7526810c32f14";
                hash32bit = "34d0e9c5ea54bfc60a0365f28b7d3a19";
            }
            if (filename == "short-n-sweet.txt") {
                hash = "e97f28bfff174f9643c088814377ada6";
                hash32bit = "5c4832a9a5510bdab5976ad0e6905e85";

            }

            var checksum = CheckMD5(Path.Combine(GetPath("Levels"), filename));
            if (checksum == hash || checksum == hash32bit) {
                return true;
            }
            throw new ArgumentException($"You've tampered with {filename}!");
            // Todo: Find out how to hide these hash strings and to avoid inline hardcode
        }

        /// <summary>
        ///  Collects a string[] containing all strings in the file
        /// </summary>
        private string[] ReadFile(string directoryName, string fileName) {
            var dir = GetPath(directoryName);
            string path = Path.Combine(dir, fileName);
            ValidatePath(path);
            return File.ReadAllLines(path);
        }

        /// <summary>
        ///  Extracts ASCII characters from the txt file and appends it
        ///  to an array. Later we will use this array to draw pictures.
        /// </summary>
        private List<char> GetAllTiles(string[] txtFile) {
            var charList = new List<char>();
            for (int i = 0; i < 23; i++) {
                foreach (var j in txtFile[i]) {
                    charList.Add(j);
                }
            }

            return charList;
        }

        /// <summary>
        ///    Adds all objects to the appropriate map being loaded
        ///    We iterate from top-left (0,1) of the screen to bottom-right (1,0)
        /// </summary>
        private void AddEntities(List<char> map) {
            float tmpX = Constants.X_MIN;
            float tmpY = Constants.Y_MAX;

            int index = 0;

            // Going from top (y 1.0) to bottom (y 0.0)
            while (tmpY > Constants.Y_MIN) {

                // Going from left (x 0.0) to right (x 1.0)
                while (tmpX < Constants.X_MAX) {

                    // There can be empty strings in our list of strings.
                    if (map[index].ToString() == " ") {
                        index += 1;

                    } else {
                        // Adds obstacles
                        if (Obstacles.ContainsKey(map[index])) {
                            var shape = new StationaryShape(new Vec2F(tmpX, tmpY),
                                new Vec2F(Constants.WIDTH, Constants.HEIGHT));
                            var file = Path.Combine(GetPath("Assets"),
                                "Images", Obstacles[map[index]]);
                            ValidatePath(file);
                            ObstacleEntities.Add(new Entity(shape, new Image(file)));
                        }

                        // Adds platforms
                        if (Platforms.ContainsKey(map[index])) {
                            var shape = new StationaryShape(new Vec2F(tmpX, tmpY),
                                new Vec2F(Constants.WIDTH, Constants.HEIGHT));
                            var file = Path.Combine(GetPath("Assets"), "Images",
                                Platforms[map[index]]);
                            ValidatePath(file);
                            PlatformEntities.Add(new Platform(shape, new Image(file), map[index]));
                        }

                        // Adds exits
                        if (Exits.ContainsKey(map[index])) {
                            var shape = new StationaryShape(new Vec2F(tmpX, tmpY),
                                new Vec2F(Constants.WIDTH, Constants.HEIGHT));
                            var file = Path.Combine(GetPath("Assets"), "Images",
                                Exits[map[index]]);
                            ValidatePath(file);
                            ExitEntities.Add(new Entity(shape, new Image(file)));
                        }

                        // Update index
                        index += 1;
                    }

                    tmpX += Constants.WIDTH;
                }

                tmpX = 0;
                tmpY -= Constants.HEIGHT;
            }
        }
    }
}

ParseCustomer.cs:

public partial class LevelParser {
    public Dictionary<string, Tuple<int, char, string, int, int, Entity>>
        GetCustomerInfo(string[] txtFile) {

        // Creates a dictionary containing all info about the customer
        var retDict = new Dictionary<string, Tuple<int, char, string, int, int, Entity>>();

        // Iterates over the entire txtFile and finds certain string
        IEnumerable<string> findName = txtFile.Where(l => l.StartsWith("Customer: "));
        foreach (var line in findName)
        {
            // Parses file
            var name = line.Split(' ')[1];
            var timeBeforeSpawn = Convert.ToInt32(line.Split(' ')[2]); // seconds
            var spawnOnPlatform = Convert.ToChar(line.Split(' ')[3]);
            var destinationPlat = line.Split(' ')[4]; // string
            var patienceTime = Convert.ToInt32(line.Split(' ')[5]); // seconds
            var rewardPoints = Convert.ToInt32(line.Split(' ')[6]);

            // Adds an entity
            var shape = new DynamicShape(new Vec2F(), new Vec2F());
            var image = new Image(Path.Combine("Assets", "Images", "CustomerStandLeft.png"));
            var entity = new Entity(shape, image);

            retDict.Add(name, new Tuple<int, char, string, int, int, Entity>(timeBeforeSpawn,
                spawnOnPlatform, destinationPlat, patienceTime, rewardPoints, entity));

        }

        // Now we have everything we need in one dictionary
        return retDict;
    }
}

还有 3 个文件,每个文件都包含相同的部分类,但有一个方法与其他文件不同。

【问题讨论】:

  • 设计模式更多的是关于如何使用代码,而不是关于如何编写代码。无论您是跨 100 个文件还是 1 个文件编写一个类,都不会对类的调用者产生影响。
  • 部分类是组织的糖。想想 winforms:部分类允许您将工具/设计器管理的代码与手动修改的代码分开。这是我能想到的最有用的应用程序。如果您觉得需要将非 gui 类拆分为部分类,我会被触发检查是否应该更好地重构。对我来说,这是“太多责任”的暗示。所有这些都与设计模式无关。

标签: c# design-patterns


【解决方案1】:

部分类在这个世界中的角色是代码生成器设计者。此外,作为开发人员,您可以利用扩展类而不会弄乱生成的代码

但是,它们在此之外的用途是有限的并且相当可疑。

至于设计模式设计模式通常是针对软件设计中给定上下文中常见问题的可重用解决方案。部分类是设计模式吗? hrmm,不是真的,就像 C# 中的 扩展方法 不是。

它们只是一点语法糖,无论如何都会被编译成一个类。

例如

public partial class Test
{
    public int testing1 {get;set;}
}

public partial class Test
{    
    public int testing2 {get;set;}
}

生成为this

public class Test
{
    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int <testing1>k__BackingField;

    [CompilerGenerated]
    [DebuggerBrowsable(DebuggerBrowsableState.Never)]
    private int <testing2>k__BackingField;

    public int testing1
    {
        [CompilerGenerated]
        get
        {
            return <testing1>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <testing1>k__BackingField = value;
        }
    }

    public int testing2
    {
        [CompilerGenerated]
        get
        {
            return <testing2>k__BackingField;
        }
        [CompilerGenerated]
        set
        {
            <testing2>k__BackingField = value;
        }
    }
}

【讨论】:

  • 指出部分类是编译器级别的概念是理解与从不依赖编译器细节但常见概念的设计模式的区别的关键。 OO 语言。例如,单例模式依赖于静态类型的 OO 概念,而不依赖于编译器细节,例如编译器如何实现此功能。
【解决方案2】:

partial class'es 只是一种将类定义拆分到多个文件的方法。

它不是设计模式的一部分,因为与在单个文件中定义的“常规”class 相比,它对class 的功能没有实际影响。

【讨论】:

  • 您对设计模式的定义不正确。设计模式不是通过查看它对类的影响来识别的。当有一个类Collection 时,从工厂模式到生成器模式的更改不会影响这个类。它们仍然是设计模式。
  • 设计模式有不同的分类。基本的是行为、结构、创造和架构设计模式。部分类概念必须至少属于这些类别之一。此外,部分类不是模式。这是一个编译器功能。模式就像是如何做事或如何完成目标的模板。
【解决方案3】:

您能说将一个类拆分为部分类是封装代码的一种方式吗?

Encapsulation 指的是一种将数据与操作该数据的方法(或其他函数)捆绑在一起的机制,从而限制对某些对象组件的直接访问。

而,

部分类提供了一种特殊的能力,可以将单个类的功能实现到多个文件中,并且在编译应用程序时,所有这些文件都会合并到一个类文件中。

因此,部分类负责跨文件的代码物理分布,而封装负责数据的逻辑分组和分类以及处理该数据的行为。

为什么将代码拆分为部分类不是设计模式的一部分?

设计模式旨在为常见的反复出现的软件设计问题提供可重用的解决方案。这些模式在逻辑层面上工作,为创建对象、定义其结构或与符合SOLID principles 的其他实体建立其行为提供解决方案。

当我们将一个类拆分为多个文件时,我们不会对类进行任何逻辑更改,从而影响其与任何其他类的关系。因此部分类不被视为设计模式。

【讨论】:

  • SOLID 不是设计模式工作的必要条件。我可以使用带有或不带有依赖倒置的工厂模式。
  • @BionicCode 我已经提到它“符合” SOLID 原则。这并不意味着设计模式必须始终使用 SOLID 原则。
  • 但我认为你的解释是更好的解释之一
  • 我明白了。但是 SOLID 不影响设计模式是否可以应用。模式也适用于不符合 SOLID 的实体。
  • 我给了你一个赞成票,但这个细节不正确。
【解决方案4】:

部分类仍然是单个类,但分布在多个文件中。部分类的用户没有意识到这个类是部分的。另一方面,封装会引入更多的类。封装是设计级别的结构设计原则,部分类是编译器级别的编译器或链接器概念。

模式必须对代码的结构、行为或架构的设计产生影响,才能被视为设计模式。设计模式通常分为创建型、结构型、架构型和行为型设计模式。部分类的概念不属于任何这些类别。部分类的概念依赖于编译器或链接器来了解这个概念。

是什么让模式成为模式?模式是在不同场景中如何做事或如何完成相同目标(解决相同问题)的模板。模式独立于编译器平台,因为它是一种独立于语言的通用解决方案。

向 C# 语言引入的部分类提供了一种将 UI 标记代码 (XAML) 与相应的代码隐藏 (C#) 分开的方法。然后编译器将合并这两个文件。在第一步中,XAML 代码由 XAML 解释器转换为 C#。然后将两个部分类合并,然后再翻译为 IL。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-26
    • 2012-02-10
    相关资源
    最近更新 更多