c# - 我试图将两个类传递给一个方法,但收到一条消息说“没有 new() 约束?
问题描述
这是我拥有的一种方法:
private static Style<ShellContent> SetGlyph(string glyph)
{
return new Style<ShellContent>().Add(new Trigger(typeof(ShellContent))
{
Property = ShellContent.IsCheckedProperty,
Value = true,
Setters =
{
new Setter()
{
Property = ShellContent.IconProperty,
Value = new RegularTabIcon() { Glyph = glyph }
},
new Setter()
{
Property = ShellContent.IconProperty,
Value = new SolidTabIcon() { Glyph = glyph }
}
}
});
}
我想改变它,这样我就可以传入RegularTabIcon、SolidTabIcon 类,并可能将它们更改为RegularTabIcon 和ThinTabIcon。
这是 RegularTabIcon 类的样子:
public class RegularTabIcon : FontImageSource
{
public RegularTabIcon()
{
FontFamily = nameof(Fonts.FaProRegular);
Size = 20;
}
}
我试图创建一个这样的通用类:
private static Style<ShellContent> SetGlyph<T1, T2>(string glyph)
{
return new Style<ShellContent>().Add(new Trigger(typeof(ShellContent))
{
Property = ShellContent.IsCheckedProperty,
Value = true,
Setters =
{
new Setter()
{
Property = ShellContent.IconProperty,
Value = new T1() { Glyph = glyph }
},
new Setter()
{
Property = ShellContent.IconProperty,
Value = new T2() { Glyph = glyph }
}
}
});
}
但我在新 T1 和新 T2 旁边收到此错误消息
does not have a new() constraint
谁能告诉我我在这里做错了什么?
另外我如何指定 T1 和 T2 必须是 type FontImageSource
?
解决方案
您必须将new()
约束添加到方法的约束。
尝试这个:
private static Style<ShellContent> SetGlyph<T1, T2>(string glyph) where T1 : new() where T2 : new()
{
return new Style<ShellContent>().Add(new Trigger(typeof(ShellContent))
{
Property = ShellContent.IsCheckedProperty,
Value = true,
Setters =
{
new Setter()
{
Property = ShellContent.IconProperty,
Value = new T1() { Glyph = glyph }
},
new Setter()
{
Property = ShellContent.IconProperty,
Value = new T2() { Glyph = glyph }
}
}
});
}
新约束指定泛型类声明中的类型参数必须具有公共无参数构造函数。
有关new()
约束的更多详细信息,您可以访问此链接:新约束(C# 参考)
更新:03.05.2021
如果您想要T1
并且T2
必须也是类型FontImageSource
,您可以将类型约束添加到方法约束,如下所示:
private static Style<ShellContent> SetGlyph<T1, T2>(string glyph) where T1 : FontImageSource, new() where T2 : FontImageSource, new()
{
return new Style<ShellContent>().Add(new Trigger(typeof(ShellContent))
{
Property = ShellContent.IsCheckedProperty,
Value = true,
Setters =
{
new Setter()
{
Property = ShellContent.IconProperty,
Value = new T1() { Glyph = glyph }
},
new Setter()
{
Property = ShellContent.IconProperty,
Value = new T2() { Glyph = glyph }
}
}
});
}
注意:如果同时使用new()
和类型约束(例如:)FontImageSource
,new()
则约束必须位于其他约束的末尾。当您将new()
约束与其他约束一起使用时,必须最后指定。
有关类型参数约束的更多详细信息,您可以访问此链接:类型参数约束(C# 编程指南)
推荐阅读
- c# - 将数据表的行附加到 Excel 并在 C# 上跳过 Excel 上的某些列
- node.js - fs readFileSync 方法可能引发哪些错误?
- aws-glue - 强制 AWS Glue 爬虫创建多个表
- javascript - Nodejs 在使用 Promise 时阻塞代码。为什么?
- c# - 如何在 ASP.NET Core 3 上通过 IoC 从 FluentValidation 启用 CascadeMode.Stop?
- java - 我可以更改工具栏“主页”图标的大小和位置吗?
- php - 如何将 php 代码中的结果转换为 html 页面
- javascript - JavaScript 交换单选按钮的输入值
- sql-server - SSIS执行SQL不返回结果
- java - 在 Selenium WebDriver 中使用自定义自动化 ID 的最佳实践是什么