[英]C# Reflection: GetProperties for 'method-like' read-only properties
UPDATE: Sorry, I was wrong, StringBar is returned.更新:抱歉,我错了,返回了 StringBar。 Let's see if I can work out how to delete this question.
让我们看看我是否能弄清楚如何删除这个问题。
Imagine the following class:想象一下下面的类:
public class Foo
{
public int Bar { get; set; }
public string StringBar
{
get { return Bar.ToString(); }
}
public void DoSomething()
{
}
}
If I write: typeof(Foo).GetProperties()
, the StringBar property info is not returned, I presume because C# thinks of it as a method, not a property.如果我写:
typeof(Foo).GetProperties()
,则不会返回 StringBar 属性信息,我认为是因为 C# 将其视为方法,而不是属性。
From a programmers perspective though, there is a difference: a method would usually be expected to cause some state change, whereas a property wouldn't.但是,从程序员的角度来看,有一个区别:方法通常会导致某些状态更改,而属性则不会。
What is the best way to get the Bar and StringBar properties, but not the DoSomething method (without specifically referring to their names obviously)?获取 Bar 和 StringBar 属性的最佳方法是什么,而不是 DoSomething 方法(显然没有特别提到它们的名称)?
I dispute your claim that StringBar won't be returned.我对您关于 StringBar 不会被退回的说法提出异议。 It's a perfectly ordinary property.
这是一个非常普通的财产。
I don't suppose in your real code it's non-public, is it?我不认为在你的真实代码中它是非公开的,是吗?
Counter-example code - with Foo
exactly as you presented it:反例代码 - 与
Foo
完全一样:
using System;
class Test
{
static void Main()
{
foreach (var prop in typeof(Foo).GetProperties())
{
Console.WriteLine(prop.Name);
}
}
}
Results:结果:
Bar
StringBar
This prints StringBar
and Bar
for me.这会为我打印
StringBar
和Bar
。
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
foreach (var item in typeof(Foo).GetProperties())
Console.WriteLine(item.Name);
Console.ReadKey();
}
public class Foo
{
public int Bar { get; set; }
public string StringBar
{
get { return Bar.ToString(); }
}
public void DoSomething()
{
}
}
}
}
Of course StringBar property will be returned!当然会返回 StringBar 属性! I'm absolutely sure!
我绝对确定! It's still a property, with get action only(read-only).
它仍然是一个属性,只有获取操作(只读)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.