通过反射获取属性,但只有用户在C#中设置属性

时间:2018-07-13 06:02:50

标签: c# reflection

我正在使用递归函数中的反射来做某事。

我想获得只有我做的属性。

public class Sample
{
    string versionInfo { get; set; } = "0.1.2.3";
}

var props_1 = typeof(Sample).GetProperties();
var props_2 = typeof(string).GetProperties();

我的意思是,我想在props_1中获得一个属性,而又不想在props_2中获得任何属性,因为我没有为字符串类型做任何事情。

我已经使用“ BindingFlags”做了一些事情。但是我做不到我想要做的。

请给我你的智慧。

谢谢。

2 个答案:

答案 0 :(得分:0)

正如@PepitoSh指出的那样,您的要求不清楚。因此,我将您的问题重新解释为:如何仅获取我声明的属性,而不是继承的类

关于这个,您可能正在寻找BindingFlags.DeclaredOnly。这是一个示例:

public class Tester
{
    public string SuperProperty { get; set; }
}

public class Test : Tester
{
    public string SubProperty { get; set; }
}

public class Program
{
    public static void Main(string[] args)
    {
        var props = typeof(Test).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);

        foreach (PropertyInfo p in props)
            Console.WriteLine(p.Name); // print only SubProperty
    }
}

答案 1 :(得分:0)

如果您要忽略不属于程序集的属性,只需对照反映的属性类型检查程序集名称

 var properties= typeof(Sample).GetProperties();
        var myAssembly = Assembly.GetCallingAssembly().FullName;
        foreach(var prop in properties)
        {
            if (Assembly.GetAssembly(prop.PropertyType).FullName.Equals(myAssembly))
                Console.WriteLine(prop.Name);// this belongs to your assembly
        }