C# LinearGradientBrush.Clone()后出现异常

C# LinearGradientBrush.Clone()后出现异常,c#,C#,从克隆的LinearGradientBrush获取InterpolationColor属性时引发异常: LinearGradientBrush brush = new LinearGradientBrush(new Point(0, 0), new Point(100, 0), Color.White , Color.Black); ColorBlend colorBlend = new ColorBlend(); colorBlend.Colors = new Color[] {Color.W

从克隆的LinearGradientBrush获取InterpolationColor属性时引发异常:

LinearGradientBrush brush = new LinearGradientBrush(new Point(0, 0), new Point(100, 0), Color.White , Color.Black);
ColorBlend colorBlend = new ColorBlend();
colorBlend.Colors = new Color[] {Color.White, Color.Red, Color.Black};
colorBlend.Positions = new float[] { 0f, 0.5f, 1f };
brush.InterpolationColors = colorBlend;
ColorBlend colorBlend1 = brush.InterpolationColors;
LinearGradientBrush brushCopy2 = (LinearGradientBrush)brush.Clone();
ColorBlend colorBlend2 = brushCopy2.InterpolationColors;

从最后一行抛出异常。

是的,给自己找一份ILSpy,或者用另一种方法来挖掘源代码,这样的问题会变得更加明显

LinearGradientBrush
有一个名为
interpolationColorsAsset

InterpolationColors
是一个调用
\u GetInterpolationColors()的属性

这又从

if (!this.interpolationColorsWasSet)
{
    throw new ArgumentException(SR.GetString("InterpolationColorsCommon", new object[]
    {
        SR.GetString("InterpolationColorsColorBlendNotSet"),
        ""
    }));
}

问题是
Clone
使用其句柄复制基础GDI笔刷,并且不努力设置此私有布尔,因此即使插值颜色可能在基础GDI笔刷中设置。您总是会遇到此错误。

这到底是什么异常?@Sayse异常是:未处理的异常:System.ArgumentException:属性必须设置为有效的ColorBlend对象才能使用互补色。ColorBlend对象必须位于相同的位置和颜色值。从0.0到1.0开始。1.0是数组中的最后一个元素。然后,如果要复制LinearGradientBrush,需要从源笔刷复制插值颜色,并将其设置为复制笔刷。是否有其他方法获取LinearGradientBrush副本?@PeytonXu实际上我怀疑您可以只执行
brushCopy2.InterpolationColors=colorBlend
,因为
\u SetInterpolationColors
方法会在内部复制它并将其封送到本机内存