小编jch*_*huk的帖子

在运行时添加通用约束?

如果有人有任何想法,我很难过.我有通用的方法

public void Foo<TClass>(TClass item) where TClass : class
{ }
Run Code Online (Sandbox Code Playgroud)

我想从另一个泛型方法调用此方法,但这个泛型方法没有类型约束"where TClass:class"

public void Bar<T>(T item)
{
    this.Foo<T>(item);
} 
Run Code Online (Sandbox Code Playgroud)

这不起作用,我得到了错误

"类型'T'必须是引用类型才能将其用作参数'TClass'"

我明白了 但我的问题是 - 我可以用C#语法做什么来"过滤"泛型类型"T",如果它是一个类,则将它传递给"this.Bar".就像是....

public void Bar<T>(T item)
{
    if (typeof(T).IsClass)
        this.Foo<T **as class**>();
} 
Run Code Online (Sandbox Code Playgroud)

我意识到我可以用反射来调用Foo,但这看起来像是在作弊.有什么我可以用C#在运行时使用约束传递"T"吗?

另外 - 我无法更改方法"Bar"的约束,因为它来自一个接口,因此约束必须匹配接口上的约束

c# generics constraints

12
推荐指数
1
解决办法
646
查看次数

以编程方式从Brushes类中获取画笔?

我有一个属性,允许将已知颜色的字符串名称发送到我的控件.酒店仅接受正确的已知颜色名称,如"红色"或"蓝色"

  private KnownColor _UseColor = KnownColor.Red;

    /// <summary>
    /// Gets or sets the name of the colour
    /// </summary>
    public string ColorName
    {
        get
        {
            return this._UseColor.ToString();
        }
        set
        {
            if (Enum.IsDefined(typeof(KnownColor), value))
                this._UseColour = (KnownColor)Enum.Parse(typeof(KnownColor), value);
        }
    }
Run Code Online (Sandbox Code Playgroud)

我想要做的是使用这个_UseColour枚举从.NET中的静态Brushes类中选择一个现有的画笔

Brush sysBrush = Brushes.FromKnownColor(this._UseColor);
e.Graphics.FillRectangle(sysBrush, 0, 0, 10, 10);
Run Code Online (Sandbox Code Playgroud)

而不是在控件被绘制时创建一个新的画笔

using (SolidBrush brsh = new SolidBrush(Color.FromKnownColor(this._UseColor)))
    e.Graphics.FillRectangle(brsh, 0, 0, 10, 10);
Run Code Online (Sandbox Code Playgroud)

有谁知道这是否可能,或者我每次都要创建一个新画笔?

Brushes.FromKnownColor不是Brushes班上的方法

c# brush brushes

5
推荐指数
1
解决办法
2593
查看次数

标签 统计

c# ×2

brush ×1

brushes ×1

constraints ×1

generics ×1