我有很多单元测试,几乎测试相同的行为.但是,数据类型会发生变化
我正在尝试创建一个可以采用任何数据类型的泛型方法.我尝试制作输入参数var但不允许这样做.另外,查看c#泛型,但通常会处理列表.
有没有办法声明泛型类型是type1 还是 type2 的泛型函数?
例:
public void Foo<T>(T number)
{
}
Run Code Online (Sandbox Code Playgroud)
我可以将T约束为int或long
在C#泛型方法中是否可以返回对象类型或Nullable类型?
例如,如果我有一个安全的索引访问器List,我想返回一个值,我可以稍后检查== null或使用或.HasValue().
我目前有以下两种方法:
static T? SafeGet<T>(List<T> list, int index) where T : struct
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
static T SafeGetObj<T>(List<T> list, int index) where T : class
{
if (list == null || index < 0 || index >= list.Count)
{
return null;
}
return list[index];
}
Run Code Online (Sandbox Code Playgroud)
如果我尝试将方法组合到一个方法中.
static T SafeGetTest<T>(List<T> list, int index)
{
if (list …Run Code Online (Sandbox Code Playgroud) 我正在开发一个应用程序,我在RichTextBox其中定制了多种类型的应用程序(RichTextBox,RichAlexBox,TransparentRichTextBox).
我想创建一个方法来接受所有这些类型加上一些其他参数.
private void ChangeFontStyle(RichTextBox,RichAlexBox,TransparentRichTextBox rch,
FontStyle style, bool add)
{
//Doing somthing with rch.Rtf
}
Run Code Online (Sandbox Code Playgroud)
我已经通过计算器搜查,发现了一些答案这样,我无法弄清楚如何使用它们来解决我的问题
void foo<TOne, TTwo>() //There's just one parameter here
where TOne : BaseOne //and I can't figure out how to define my other two parameters
where TTwo : BaseTwo
Run Code Online (Sandbox Code Playgroud)
我也试过重载,因为这个答案提供,
private void ChangeFontStyle(TransparentRichTextBox rch, FontStyle style, bool add);
private void ChangeFontStyle(RichAlexBox rch, FontStyle style, bool add);
private void ChangeFontStyle(RichTextBox rch,FontStyle style, bool add)
{
//Some codes …Run Code Online (Sandbox Code Playgroud)