【问题标题】:calling the constructor of a base class from a derived class after modifying data修改数据后从派生类调用基类的构造函数
【发布时间】:2017-08-16 16:16:26
【问题描述】:

首先,很抱歉,如果已经问过这个问题,但我一直在谷歌搜索,但没有找到任何解决方案。我在想也许我只是不知道如何正确地表达这个问题。

public class WeatherEngine : ParticleEngine
{
    public enum WeatherType
    {
        None,
        Rain,
        Snow
    }
    public WeatherEngine(List<Texture2D> weatherTextures, WeatherType weatherType) : base(weatherTextures, null)
    {}

我目前正在尝试从我的粒子引擎派生我的天气类,但我很难弄清楚是否有办法在将某些数据传递到基类构造函数之前对其进行修改。

理想情况下,我希望能够为每种天气类型传递可能的天气纹理的完整列表,然后将该列表分成另一个列表List&lt;Texture2D&gt; currentWeatherTextures 以传递给基本构造函数。

AFAIK,我唯一的其他选择是在调用 Wea​​therEngine 的构造函数之前分离列表,但本着保持我的主类大部分逻辑清晰的精神,而不是仅使用它来初始化所有内容,我希望有一个替代方案解决方案。

或者我是否应该根本不从 ParticleEngine 派生 WeatherEngine,并将两者分开?

【问题讨论】:

    标签: c# monogame


    【解决方案1】:

    您可以只在派生类中创建一个私有静态方法来修改数据并返回值以传递给基类的构造函数:

    using System;
    
    namespace ConsoleApp2
    {
        public class Base
        {
            public Base(string param)
            {
                Console.WriteLine("Param: " + param);
            }
        }
    
        public class Derived : Base
        {
            public Derived(string param) : base(Modify(param))
            {
            }
    
            static string Modify(string s)
            {
                return "Modified: " + s;
            }
        }
    
        class Program
        {
            static void Main()
            {
                Derived d = new Derived("Test");
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2015-08-18
      • 2016-07-19
      • 2011-05-03
      • 2018-07-21
      • 2018-07-16
      • 2011-09-27
      • 2019-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多