![](/img/trans.png)
[英]C# 6.0 Reflection: Extract the name of backing fields of read-only auto properties
[英]C# Reflection: GetProperties for 'method-like' read-only properties
更新:抱歉,我錯了,返回了 StringBar。 讓我們看看我是否能弄清楚如何刪除這個問題。
想象一下下面的類:
public class Foo
{
public int Bar { get; set; }
public string StringBar
{
get { return Bar.ToString(); }
}
public void DoSomething()
{
}
}
如果我寫: typeof(Foo).GetProperties()
,則不會返回 StringBar 屬性信息,我認為是因為 C# 將其視為方法,而不是屬性。
但是,從程序員的角度來看,有一個區別:方法通常會導致某些狀態更改,而屬性則不會。
獲取 Bar 和 StringBar 屬性的最佳方法是什么,而不是 DoSomething 方法(顯然沒有特別提到它們的名稱)?
我對您關於 StringBar 不會被退回的說法提出異議。 這是一個非常普通的財產。
我不認為在你的真實代碼中它是非公開的,是嗎?
反例代碼 - 與Foo
完全一樣:
using System;
class Test
{
static void Main()
{
foreach (var prop in typeof(Foo).GetProperties())
{
Console.WriteLine(prop.Name);
}
}
}
結果:
Bar
StringBar
這會為我打印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()
{
}
}
}
}
當然會返回 StringBar 屬性! 我絕對確定! 它仍然是一個屬性,只有獲取操作(只讀)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.