我想在Java中实现一个通用的扩展方法,就像我在C#中做的那样。
以下是我的C#代码:
DataRecordExtensions.cs
public static class DataRecordExtensions
{
public static T Get<T>(this IDataRecord record, string fieldName, T defaultVal = default(T))
{
object o = record[fieldName];
if (o != null && !DBNull.Value.Equals(o))
{
try
{
return (T)Convert.ChangeType(o, typeof(T));
}
catch
{
}
}
return defaultVal;
}
}
字符串
下面是我如何使用它的DataRecordExtensions方法:
CountryRepository.cs
public class CountryRepository : ICountryRepository
{
// ... here are some code not relevant to understand my problem
public IEnumerable<Country> LoadCountries()
{
List<Country> countries = new List<Country>();
using (var sqlConnection = new SqlConnection(this.connectionString))
{
sqlConnection.Open();
string sqlTxt = "SELECT * FROM tab_Countries ORDER BY SortID";
using (SqlCommand readCmd = new SqlCommand(sqlTxt, sqlConnection))
{
SqlDataReader countriesReader = readCmd.ExecuteReader();
while (countriesReader.Read())
{
Country c = new Country();
c.CountryCode = countriesReader.Get<string>("CountryID");
c.Country = countriesReader.Get<string>("Country");
c.SortID = countriesReader.Get<int>("SortID");
countries.Add(c);
}
readCmd.Dispose();
countriesReader.Dispose();
};
sqlConnection.Close();
}
return countries;
}
}
型
就像你看到的,我使用**countriesReader.Get< string >(“CountryID”)**现在我想在Java中使用这样的东西。我如何在Java中使用这样的扩展方法,或者有其他选择吗?
1条答案
按热度按时间0h4hbjxa1#
在Java中,你也可以这样调用一个方法。
字符串
它可以被称为
型