I am trying to use reflection to get all class methods. I want to prepare an algorithm that will recognize which methods are getters and setters.
So, as you see I am printing each getter in the format: {name} will return {Return Type}
. I am trying to print all of the setters in the format: {name} will set field of {Parameter Type}
, but I don't know how to get the Parameter Type
.
public string CollectGettersAndSetters(string className)
{
Type classType = Type.GetType(className);
MethodInfo[] getters = classType
.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Where(m => m.Name.StartsWith("get"))
.ToArray();
MethodInfo[] setters = classType
.GetMethods(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)
.Where(m => m.Name.StartsWith("set"))
.ToArray();
StringBuilder sb = new StringBuilder();
foreach (MethodInfo getter in getters)
{
sb.AppendLine($"{getter.Name} will return {getter.ReturnType}");
}
foreach (MethodInfo setter in setters)
{
sb.AppendLine($"{setter.Name} will set field of {?}");
}
return sb.ToString().TrimEnd();
}
An example of class for which I will use the method:
public class Hacker
{
public string username = "securityGod82";
private string password = "mySuperSecretPassw0rd";
public string Password
{
get => this.password;
set => this.password = value;
}
private int Id { get; set; }
public double BankAccountBalance { get; private set; }
public void DownloadAllBankAccountsInTheWorld()
{
}
}
The expected output is:
get_Password will return System.String
get_Id will return System.Int32
get_BankAccountBalance will return System.Double
set_Password will set field of System.String
set_Id will set field of System.Int32
set_BankAccountBalance will set field of System.Double
Thank you in advance!
Aucun commentaire:
Enregistrer un commentaire