Skip to main content
 首页 » 编程设计

c#之如何向泛型方法添加参数

2024年02月20日11dudu

我有以下方法:

    public static IEnumerable<SelectListItem> GetSpacedOptions<T>() where T : struct 
    { 
        var t = typeof(T); 
        if (!t.IsEnum) 
        { 
            throw new ArgumentException("Not an enum type"); 
        } 
        var options = Enum.GetValues(t).Cast<T>() 
            .Select(x => new SelectListItem 
            { 
                Value = ((int) Enum.ToObject(t, x)).ToString(), 
                Text = Regex.Replace(x.ToString(), "([A-Z])", " $1").Trim() 
            }); 
        return options; 
    } 

我需要做的是添加一个名为 zeroPad 的 bool 参数。因此,如果未提供,方法将保持不变,但如果提供,则文本输出将始终是两位数的字符串,例如“01”、“04”或“77”。

如何添加该参数。好像没地方加。

请您参考如下方法:

如何提供默认值 false。-

public static IEnumerable<TestClass> GetSpacedOptions<T>(bool zeroPad = false) 
                                              where T : struct 

用户可以通过两种方式调用它 -

GetSpacedOptions<MyEnum>(true); 

如果未指定值,zeroPad 值默认为false

GetSpacedOptions<MyEnum>();