将 object 插入具有不同基类型(继承)的值中 c#

Insert object into value with different base type (inherited) c#

所以我有一个 SvgElement that contains a value of SvgPath 类型的 object(它继承了 SvgElement)。这是代码。

SvgElement createdElement;
//other operations. createdElement now has other data of SvgPath

if (createdElement.GetType() == typeof(SvgPath) & createdElement.ElementName == "path" && storedValue != "")
 createdElement.PathData = SvgPathBuilder.Parse(storedValue);

return createdElement

(注意:这是在 unity 中完成的,必须考虑 .net 2.0,因为 Unity 会冒犯 System.Linq)

现在 SvgPathBuilder.Parsestring 和 returns 类型 SvgPathSegmentList 的 object 转换为 PathDataPathData 通常是 SvgPath 中的一个变量,但我修改了 SvgElement 以临时获取该值,这样我就知道我正在测试的其他东西是否有效。

现在我已经给了你背景信息..我如何(通用代码 - T 型东西)编写它以便 SvgPathBuilder.Parse 将存储在 SvgPath.PathData 而不是继承的基础 SvgElement 的 PathData?

(不确定标题是否符合问题,请指教)

从单纯的描述中不太清楚你想要实现什么,但考虑以下设计,仍需要进一步修改以适应确切的要求

重要细节:

  • SvgElement 用 abstract 属性 做了抽象,需要 Child 实现,即 SvgPath
  • TestSVG 中使用的通用约束以确保我们始终提供正确的 class 或其派生版本,在此 class 中您可以实现 [=25] 的填充=]路径数据

        public abstract class SvgElement
        {
          public abstract List<SvgPath> PathData { get; set;}
        }
    
        public class SvgPath : SvgElement
        {
          public override List<SvgPath> PathData { get; set;}       
        }
    
        public class TestSvg<T> where T:SvgElement
        {
    
        }
    

您可以将元素转换为 SvgPath: (createdElement as SvgPath).PathData = SvgPathBuilder.Parse‌​(storedValue);