使方法泛型
本文关键字:泛型 方法 | 更新日期: 2023-09-27 17:53:22
我有一个从特定对象中提取日期名称的方法,像这样:
private string ExtractWeekDayNames(FiscalReceipt fiscalReceipt)
{
string retVal = "";
Dictionary<string, bool> WeekDays =
new Dictionary<string, bool>() {
{ "Sun", fiscalReceipt.Sunday },
{ "Mon", fiscalReceipt.Monday },
{ "Tue", fiscalReceipt.Tuesday },
{ "Wed", fiscalReceipt.Wednesday },
{ "Thu", fiscalReceipt.Thursday },
{ "Fri", fiscalReceipt.Friday },
{ "Sat", fiscalReceipt.Saturday }
};
//Find week days
foreach (var item in WeekDays)
{
if (item.Value == true)
retVal += item.Key + ",";
}
if (!string.IsNullOrEmpty(retVal))
retVal = retVal.Substring(0, retVal.Length - 1);
return retVal;
}
我也有一个类似的方法来执行相同的操作但是有不同类型的参数,比如:
private string ExtractWeekDayNames(NonFiscalReceipt nonFiscalReceipt)
{
...
}
NonFiscalReceipt也有Sunday, Monday等属性。
我如何用一个方法代替这两个方法?
public class FiscalReceipt : Receipt{
FiscalReceipt specific fields
}
public class NonFiscalReceipt : Receipt{
NonFiscalReceipt specific fields..
}
public class Receipt{
fields common to both classes
}
private string ExtractWeekDayNames(Receipt receipt){
}
两种类型的收据都继承自收据,也就是说,你可以传入其中一种,仍然会有所有的字段:)
您需要为您的类创建一个要实现的公共接口,以便该方法可以接受实现该接口的任何内容。
interface IReceipt
{
bool Sunday {get; }
bool Monday {get; }
...
bool Saturday {get; }
}
那么你的方法应该是这样的:
private string ExtractWeekDayNames<T>(T receipt) where T : IReceipt
{
string retVal = "";
Dictionary<string, bool> WeekDays =
new Dictionary<string, bool>() {
{ "Sun", receipt.Sunday },
{ "Mon", fiscalReceipt.Monday },
{ "Tue", receipt.Tuesday },
{ "Wed", receipt.Wednesday },
{ "Thu", receipt.Thursday },
{ "Fri", receipt.Friday },
{ "Sat", receipt.Saturday }
};
//Find week days
foreach (var item in WeekDays)
{
if (item.Value == true)
retVal += item.Key + ",";
}
if (!string.IsNullOrEmpty(retVal))
retVal = retVal.Substring(0, retVal.Length - 1);
return retVal;
}
然而,正如juharr和Remy Grandin在注释中正确地写道——在这种情况下不需要泛型——您可以简单地将接口传递给方法:
private string ExtractWeekDayNames(IReceipt receipt)
{
string retVal = "";
Dictionary<string, bool> WeekDays =
new Dictionary<string, bool>() {
{ "Sun", receipt.Sunday },
{ "Mon", receipt.Monday },
{ "Tue", receipt.Tuesday },
{ "Wed", receipt.Wednesday },
{ "Thu", receipt.Thursday },
{ "Fri", receipt.Friday },
{ "Sat", receipt.Saturday }
};
//Find week days
foreach (var item in WeekDays)
{
if (item.Value == true)
retVal += item.Key + ",";
}
if (!string.IsNullOrEmpty(retVal))
retVal = retVal.Substring(0, retVal.Length - 1);
return retVal;
}
为NonFiscalReceipt
和FiscalReceipt
创建包含共同属性的基接口:
public interface IReceipt
{
bool Sunday{get;}
......
}
替换方法签名:private string ExtractWeekDayNames(IReceipt fiscalReceipt)
尽量使用DayOfWeek
enum。