gpt4 book ai didi

c# - 在 Visual Studio c# 中基于源库创建自己的库

转载 作者:行者123 更新时间:2023-11-30 22:05:18 24 4
gpt4 key购买 nike

我意识到现有库(即 System.Windows.Forms.DataVisualization.Charting)不支持某些方法。例如,如果我希望系列绘制 ​​x 和 y 值,包括 x 中的增量等参数。

如何在现有的系统库中添加另一个重载方法,我的主管提到了一种称为 Facade 模式和 Adapter 模式的常用技术,但我真的不知道如何处理这些事情。

谢谢

我处理这个问题的方法是创建自己的类,继承这些库...但是后来我意识到工作量太大了,因为Windows Forms创建的所有代码都使用系统中的库,而不是我的库...例如this.chart1 = new System.Windows.Forms.DataVisualization.Charting.Chart(); 他们正在使用 Charting.Chart,如果我创建自己的名为 Mychart 的图表类,我将不得不用 mychart 替换每个图表.....我该如何避免这种情况?

是不是要在不做太多工作的情况下将一些新的重载方法附加到 Microsoft 库中?

最佳答案

您是否考虑过使用 Extension Methods

扩展方法为您提供了一种在不更改现有程序集的情况下向现有程序集添加功能的方法。您可以添加重载方法,而无需更改原始程序集,也无需更改使用该程序集的当前现有代码。

注意扩展方法有限制。

如果你想向 System.Windows.Forms.DataVisualization.Charting.Chart 类添加一个新的重载扩展方法,那么你可以尝试这样的事情:

向您的项目添加一个包含扩展方法的静态类:

public static class ChartExtensions
{
public static void Show(this Chart chart, bool includeIncrements)
{
// Do your modifications to the chart here ...
chart.Show();
}

}

现在您可以对普通图表对象使用新方法:

Chart chart1 = new Chart();  // <-- Normal chart object
//chart1.Show(); // <-- standard chart method
chart1.Show(true); // <-- your new overloaded method

编辑:不确定您到底想要什么。也许是这样的?

public static class DataPointCollectionExtension
{
// Adds a new point to the end of the collection, with a spedified y and
// a value of x that is dx larger than the last value.
public static void AddDXY(this DataPointCollection points, double dx, double y)
{
double x = 0.0; // Default starting x if there are no points in the collection.
if (points.Count() > 0) { x = points.Last().XValue + dx; }

points.Add(new DataPoint(x, y));
}
}

然后像这样使用:

chart1.Series[0].Points.AddDXY(0.5, 5.2);
chart1.Series[0].Points.AddDXY(0.5, 4.2);
chart1.Series[0].Points.AddDXY(1.0, 6.2);
chart1.Series[0].Points.AddDXY(0.7, 4.8);

关于c# - 在 Visual Studio c# 中基于源库创建自己的库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24492658/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com