简体   繁体   中英

In java we can derived the class from abstract class in function itself. Can we do for C# also?

In Java we can derive the class from abstract class in function itself.

Can we do the same thing for C#?

public class A {
     public final static A d = new A();
    protected abstract class M {
        public int getValue() {
            return 0;
        }
    }

    protected static M[] c = null;
     public final static void Foo() {
        if (c == null) {
            M[] temp = new M[] {
                d.new M() {
                    public int getValue() {
                        return 1;
                    }
                },
                d.new M() {
                    public int getValue() {
                        return 2;
                    }
                },
                d.new M() {
                    public int getValue() {
                        return 3;
                    }
                }
            };
            c = temp;
        }
    }
}

No, there's no equivalent of anonymous inner classes in C#.

Typically for single-method abstract classes or interfaces, you'd use a delegate in C# instead, and often use a lambda expression to create instances.

So something similar to your code would be:

public class A 
{
    public delegate int Int32Func();

    private static Int32Func[] functions;

    // Note: this is *not* thread safe...
    public static void Foo() {
        if (functions == null) {
            functions = new Int32Func[]
            {
                () => 1,
                () => 2,
                () => 3
            };
        }
    }
}

... except that I'd use Func<int> instead of declaring my own delegate type.

Just to add a reference to Jon Skeet's answer. Anonymous Types in C# can only define public readonly properties. See excerpt from the C# Programming guide (found here https://msdn.microsoft.com/en-us/library/bb397696.aspx ):

Anonymous types contain one or more public read-only properties. No other kinds of class members, such as methods or events, are valid. The expression that is used to initialize a property cannot be null, an anonymous function, or a pointer type.

So short answer (as Jon has already stated) is anonymous types cannot have methods but you can use anonymous functions or delegates to get the same behavior in most cases.

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