You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#中为Point子类实现通用AdaptMeshPoints方法的技术需求

我来帮你搞定这个C#泛型方法的实现问题,先梳理下现有代码的问题,再给出符合需求的完整解决方案:

首先修正原始类定义的问题

你的原始类里有几个编译级别的问题,比如Point的x和y是私有字段,外部方法和子类没法直接访问;子类没有显式调用父类的构造函数,会导致编译失败;还有子类的字段也是私有,外部没法获取。我先调整成符合C#规范的版本:

public class Point
{
    // 改成公共属性,方便外部和子类访问修改
    public double X { get; set; }
    public double Y { get; set; }

    public Point(double pos_x, double pos_y)
    {
        X = pos_x;
        Y = pos_y;
    }
}

public class ColorPoint : Point
{
    // 改成公共属性,支持外部访问
    public double Color { get; set; }

    // 必须显式调用父类构造函数,因为父类没有无参构造
    public ColorPoint(double x, double y, double color) : base(x, y)
    {
        Color = color;
    }
}

public class AmountPoint : Point
{
    // 改成公共属性,支持外部访问
    public int Amount { get; set; }

    public AmountPoint(double x, double y, int amount) : base(x, y)
    {
        Amount = amount;
    }
}

实现符合需求的AdaptMeshPoints方法

你的两个需求:修改公共参数、打印指定子类参数,我用泛型+委托的方式实现,既保证类型安全,又灵活支持不同子类的属性打印:

using System;
using System.Collections.Generic;

public class MainClass
{
    public static void Main()
    {
        // 测试ColorPoint场景
        var colorList = new List<ColorPoint>
        {
            new ColorPoint(10, 20, 150),
            new ColorPoint(30, 40, 200)
        };
        // 调用方法:修改公共坐标,指定打印Color属性
        AdaptMeshPoints(colorList, cp => cp.Color);

        // 测试AmountPoint场景
        var amountList = new List<AmountPoint>
        {
            new AmountPoint(5, 5, 10),
            new AmountPoint(15, 15, 25)
        };
        // 调用方法:修改公共坐标,指定打印Amount属性
        AdaptMeshPoints(amountList, ap => ap.Amount);
    }

    /// <summary>
    /// 修改Point子类列表的公共坐标参数,并打印指定的子类属性
    /// </summary>
    /// <typeparam name="T">约束为Point的子类,确保能访问公共坐标</typeparam>
    /// <param name="pointList">要处理的Point子类列表</param>
    /// <param name="propertySelector">委托,用于选择要打印的子类属性</param>
    /// <returns>返回修改后的列表</returns>
    public static List<T> AdaptMeshPoints<T>(List<T> pointList, Func<T, object> propertySelector) where T : Point
    {
        // 防御性检查,避免空列表导致异常
        if (pointList == null || pointList.Count == 0)
        {
            throw new ArgumentException("传入的Point列表不能为空");
        }

        // 修改公共参数:这里以第一个点的X坐标为例
        pointList[0].X = 45;
        Console.WriteLine($"修改后第一个点的X坐标:{pointList[0].X}");

        // 打印指定的子类参数
        var targetValue = propertySelector(pointList[0]);
        Console.WriteLine($"第一个点的指定属性值:{targetValue}");

        return pointList;
    }
}

关键细节说明

  • 泛型约束:where T : Point确保传入的类型是Point的子类,这样我们可以安全地访问X、Y这些公共参数。
  • 委托传参:用Func<T, object>让调用者可以灵活指定要打印的属性(比如cp => cp.Color),这比你示例里直接传变量名的写法更符合C#的类型安全规则,也更灵活。
  • 访问权限调整:把私有字段改成公共属性是C#的最佳实践,既保证外部可以访问修改,又保留了封装性(如果需要控制读写,可以调整get/set权限)。
  • 防御性编程:添加了空列表检查,避免运行时出现空引用异常。

内容的提问来源于stack exchange,提问作者Pixel_95

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 06:25:25