开发者

C# Reflection: GetProperties for 'method-like' read-only properties

UPDATE: Sorry, I was wrong, StringBar is returned. 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.

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 speci开发者_JS百科fically referring to their names obviously)?


I dispute your claim that StringBar won't be returned. 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:

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.

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! I'm absolutely sure! It's still a property, with get action only(read-only).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜