你怎么发现只有同时具有一个getter和setter属性? [英] How do you find only properties that have both a getter and setter?
问题描述
C#.NET 3.5
C#, .NET 3.5
我试图让所有的既有getter和一个setter的实例对象的属性。在code我的认为的应该是
I am trying to get all of the properties of an object that have BOTH a getter and a setter for the instance. The code I thought should work is
PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
然而,结果包括不具有一个设置器的属性。给你我的继承结构的可能影响本(虽然我不知道如何),一个简单的想法:
However, the results include a property that does not have a setter. To give you a simple idea of my inheritance structure that might be affecting this (though I don't know how):
public interface IModel
{
string Name { get; }
}
public class BaseModel<TType> : IModel
{
public virtual string Name { get { return "Foo"; } }
public void ReflectionCopyTo(TType target)
{
PropertyInfo[] infos = this.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
foreach (PropertyInfo info in infos)
info.SetValue(target, info.GetValue(this, null), null);
}
}
public class Child : BaseModel<Child>
{
// I do nothing to override the Name property here
}
我结束了以下错误与名称工作时:
I end up with the following error when working with Name:
System.ArgumentException: Property set method not found.
编辑:我想知道为什么这样做的没有的工作,以及我应该怎样做才能不出现错误
I would like to know why this does not work, as well as what I should be doing to not get the error.
推荐答案
呼叫<一href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getgetmethod.aspx"><$c$c>GetGetMethod$c$c>和<一href="http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getsetmethod.aspx"><$c$c>GetSetMethod$c$c>对物业 - 如果这两个结果都是非空,你在那里:)
Call GetGetMethod
and GetSetMethod
on the property - if both results are non-null, you're there :)
(无参数的版本只返回public方法;有过载用布尔参数指定是否你也想非公开方式)
(The parameterless versions only return public methods; there's an overload with a boolean parameter to specify whether or not you also want non-public methods.)
这篇关于你怎么发现只有同时具有一个getter和setter属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!