案例一:
以下是实体类:
class Gneral
{
protected string Str { get; set; } = "你好,受保护的变量";
string Str1 { get; set; } = "你好";
public bool Str2 { get; set; } = true;
}
以下是获取属性的方法:
/// <summary>
/// 这是获取公开属性的方法
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <param name="propertyname"></param>
/// <returns></returns>
public static string GetObjectPropertyValue<T>(T t, string propertyname)
{
Type type = typeof(T);
PropertyInfo property = type.GetProperty(propertyname);
if (property == null) return string.Empty;
object o = property.GetValue(t, null);
if (o == null) return string.Empty;
return o.ToString();
}
以下是使用的案例:
class Program
{
static Gneral gneral = new Gneral();
static void Main(string[] args)
{
result = GetObjectPropertyValue(gneral, "Str");
Console.WriteLine(result);
result = GetObjectPropertyValue(gneral, "Str1");
Console.WriteLine(result);
result =GetObjectPropertyValue(gneral, "Str2");
Console.WriteLine(result);
Console.WriteLine("*********************************************");
var hProperties = typeof(Gneral).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);//获取非公开属性
foreach (var item in hProperties)
{
if (item.Name== "Str")
{
Console.WriteLine(item.GetValue(gneral));//获取反射后各属性的值
}
}
Console.ReadLine();
}
显示的结果:
案例二:
以下是抽象父类:
abstract class BaseClass
{
protected bool Isruning { get; set; } = false;
}
以下是继承的子类:
class TestRefletion : BaseClass//继承上面的父类
{
public static TestRefletion Cur = new TestRefletion();//单例模式
protected bool Isrun = true;
private TestRefletion()
{
test();
}
void test()
{
if (!Isruning)
{
Isruning = true ;
}
}
}
以下是使用:
写在方法中就行。
TestRefletion testRefletion = TestRefletion.Cur;
var hProperties1 = typeof(TestRefletion).GetProperties(BindingFlags.NonPublic | BindingFlags.Instance);//获取非公开属性
foreach (var item in hProperties1)
{
if (item.Name == "Isruning")//判断是否是我要的那个属性
{
Console.WriteLine(item.GetValue(testRefletion));//获取反射后各属性的值
}
}
展示结果: