C# 类型泛型参数确定

本文关键字:参数 泛型 类型 | 更新日期: 2023-09-27 18:30:35

我在自动类型确定方面遇到问题。我正在尝试为通用 Rtf 样式创建创建通用方法(RtfElement.StyleOfType<,>)。但是编译器不假定此关键字为TElement : RtfElement类型。我不知道为什么会发生这种情况,因为TElementRtfElement类型限制。

/// <summary>
/// Abstract Rtf style.
/// </summary>
public abstract class RtfStyle<TElement>
    where TElement : RtfElement
{
    /// <summary>
    /// Creates Rtf style of the given type.
    /// </summary>
    /// <typeparam name="TStyle">Rtf style type</typeparam>
    /// <param name="styleOwner">Style owner</param>
    /// <returns>Rtf style</returns>
    public static TStyle Create<TStyle>(TElement styleOwner)
        where TStyle : RtfStyle<TElement>, new()
    {
        if (styleOwner == null)
        {
            throw new ArgumentNullException("styleOwner");
        }
        return new TStyle
        {
            StyleOwner = styleOwner
        };
    }
    #region Protected Fields
    protected TElement StyleOwner;
    #endregion
}

无法在此行编译以下代码:

style = RtfStyle<TElement>.Create<TStyle>(this);

编译器错误:"this is not assignable to parameter type TElement":

/// <summary>
/// Abstract Rtf element.
/// </summary>
public abstract class RtfElement
{
    /// <summary>
    /// Gets Rtf style of the given type.
    /// </summary>
    /// <typeparam name="TElement">Rtf element type</typeparam>
    /// <typeparam name="TStyle">Rtf style type</typeparam>
    /// <returns>Rtf style</returns>
    protected TStyle StyleOfType<TElement, TStyle>()
        where TElement : RtfElement
        where TStyle : RtfStyle<TElement>, new()
    {
        var style = Style.OfType<TStyle>().FirstOrDefault();
        if (style != null)
        {
            return style;
        }
        style = RtfStyle<TElement>.Create<TStyle>(this);
        Style.Add(style);
        return style;
    }
    #region Protected Fields
    protected readonly List<IRtfWritable> Style = new List<IRtfWritable>();
    #endregion
}

C# 类型泛型参数确定

给定以下代码行

style = RtfStyle<TElement>.Create<TStyle>(this);

发生的情况是,您在RtfStyle<TElement>中调用一个名为 Create 的静态方法,类型为 TStyle 。这意味着该方法的参数必须TElement ,并且您正在发送this

由于thisRtfElement不继承TElement - 您的代码无法编译。