有一种方法可以在C#中实现初始化实例的抽象方法,就像在Java中一样?
public static abstract class A
{
public abstract String GetMsg();
public void Print()
{
System.out.println(GetMsg());
}
}
public static void main(String[] args)
{
A a = new A()
{
@Override
public String GetMsg()
{
return "Hello";
}
};
a.Print();
}
答案 0 :(得分:7)
不,你不能 - 但你可以使用Func<string>
:
using System;
namespace Demo
{
public sealed class A
{
public Func<string> GetMsg { get; }
public A(Func<string> getMsg)
{
GetMsg = getMsg;
}
public void Print()
{
Console.WriteLine(GetMsg());
}
}
public static class Program
{
public static void Main()
{
var a = new A(() => "Hello");
a.Print();
}
}
}
或者,如果您希望能够在初始化后更改GetMsg
属性:
using System;
namespace Demo
{
public sealed class A
{
public Func<string> GetMsg { get; set; } = () => "Default";
public void Print()
{
Console.WriteLine(GetMsg());
}
}
public static class Program
{
public static void Main()
{
var a = new A(){ GetMsg = () => "Hello" };
a.Print();
}
}
}
(这使用了c#6语法 - 你必须为早期版本略微修改它。)