Created
August 17, 2020 13:51
-
-
Save mikegoatly/216762e1bb7659f46a3dd2d8952b0c1d to your computer and use it in GitHub Desktop.
Reverse engineering read/write properties of a type
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
void Main() | |
{ | |
Console.WriteLine(GetDefinition<Test>()); | |
/* Prints: | |
public class Test | |
{ | |
public System.Int32 Number { get; set; } | |
public System.String Name { get; set; } | |
} | |
*/ | |
} | |
public static string GetDefinition<T>() | |
{ | |
var builder = new StringBuilder(); | |
var type = typeof(T); | |
builder.Append("public class ") | |
.AppendLine(type.Name) | |
.AppendLine("{"); | |
var readWriteProperties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance) | |
.Where(p => p.CanRead && p.CanWrite); | |
foreach (var property in readWriteProperties) | |
{ | |
builder.Append(" public ") | |
.Append(property.PropertyType.FullName) | |
.Append(" ") | |
.Append(property.Name) | |
.AppendLine(" { get; set; }"); | |
} | |
builder.AppendLine("}"); | |
return builder.ToString(); | |
} | |
public class Test | |
{ | |
public int Number { get; set; } | |
public string Name { get; set; } | |
public bool ReadOnly {get;} | |
private bool Hidden {get;set;} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment