什麼你看是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; }
}
上面的代碼的問題類屬性的名稱時,我們不能重複使用其他類型的,說我們希望也得到一個Type
命名School
特性,我們會不斷創造新的方法來獲得任何給定的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; }
}
的屬性要解決這個問題,我們美國EA 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; }
}
所以這意味着'方法'只用於確定方法的類型? –
2014-10-09 01:07:18
@LeoSarmiento'type'可以是方法中某些變量的類型,方法的任何參數/返回類型。此外,它可以用作某種通用方法的類型參數,從該方法調用。 – 2014-10-09 01:10:07
@MadSorcerer現在我知道了,謝謝你的迴應。 – 2014-10-09 01:12:38