Mat*_*att 33 .net c# reflection
C#,.NET 3.5
我试图获得一个对象的所有属性,它们具有实例的getter和setter.我认为应该工作的代码是
PropertyInfo[] infos = source.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.GetProperty);
Run Code Online (Sandbox Code Playgroud)
但是,结果包括没有setter的属性.为了简单介绍一下可能影响它的继承结构(虽然我不知道如何):
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
}
Run Code Online (Sandbox Code Playgroud)
使用Name时,我最终得到以下错误:
System.ArgumentException: Property set method not found.
Run Code Online (Sandbox Code Playgroud)
编辑:我想知道为什么这并没有工作,还有什么我应该怎样做才能不出现错误.
Jon*_*eet 41
调用GetGetMethod
并GetSetMethod
在属性上 - 如果两个结果都是非null,那么你就在那里:)
(无参数版本只返回公共方法;有一个带有布尔参数的重载,用于指定是否还需要非公共方法.)
小智 33
您可以查看PropertyInfo.CanRead
和PropertyInfo.CanWrite
属性.
Tim*_*vis 30
怎么样...
var qry = typeof(Foo).GetProperties(BindingFlags.Instance | BindingFlags.Public)
.Where(p => p.CanRead && p.CanWrite);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12115 次 |
最近记录: |