简体   繁体   中英

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 specifically 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM