您正在查看的是Generic Method。它们用于重用代码库中包含的逻辑,您在这些尖括号之间看到的是所谓的Type Parameter。
Type Parameters 用于return 指定的Type,或者用于指定参数的类型。
例如,假设我们要获取名为 User 的类的属性名称
public IEnumerable<string> GetUserProperties()
{
return typeof(User).GetProperties().Select(property => property.Name);
}
public class User
{
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
上面代码的问题是我们不能将它重用于其他类型,假设我们还想获取名为School 的Type 的属性,我们将不断创建新方法来获取任何给定 Type 的属性
public IEnumerable<string> GetSchoolProperties()
{
return typeof(School).GetProperties().Select(property => property.Name);
}
public class School
{
public string SchoolId { get; set; }
public string Name { get; set; }
}
为了解决这个问题,我们使用Generic Method,这种方法不仅限于一个Type(尽管可以将约束应用于类型参数,但它们暂时超出了范围,请尝试先把你的想法包起来)
void Main()
{
User user = new User
{
FirstName = "Aydin",
LastName = "Aydin",
UserId = Guid.NewGuid().ToString()
};
School school = new School
{
SchoolId = Guid.NewGuid().ToString(),
Name = "Aydins school"
};
var userProperties = GetProperties(user);
var schoolProperties = GetProperties(school);
Console.WriteLine ("Retrieving the properties on the User class");
foreach (var property in userProperties)
{
Console.WriteLine ("> {0}", property);
}
Console.WriteLine ("\nRetrieving the properties on the School class");
foreach (var property in schoolProperties)
{
Console.WriteLine ("> {0}", property);
}
}
public static IEnumerable<string> GetProperties<T>(T t)
{
return t.GetType().GetProperties().Select(property => property.Name);
}
public class User
{
public string UserId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class School
{
public string SchoolId { get; set; }
public string Name { get; set; }
}