我知道這已被覆蓋之前,但我還沒有找到任何好的解決方案。在這個例子中,我使用了兩個帶返回參數類的返回類型類(ClassA和ClassB)。我有一個基類,我的ClassXml和ClassText擴展並希望防止打印中的特定接口強制轉換。這可能嗎?C#返回類型重協方差
調用ClassXml和ClassText Execute方法,後者又調用調用相應打印的基類功能。
using System;
namespace ConsoleApplication1
{
internal class Program
{
public class ClassA
{
public string Xml
{
get { return "xml"; }
}
}
public class ClassB
{
public char Text
{
get { return 't'; }
}
}
public interface IReturnArgs<out T>
{
string Name { get; set; }
T Source { get; }
}
public class ReturnArgs<T> : IReturnArgs<T>
where T : class
{
public string Name { get; set; }
private T _source;
public T Source
{
get { return _source ?? (_source = (T) Activator.CreateInstance(typeof (T), new object[] {})); }
}
}
private static void Main(string[] args)
{
var classA = new ReturnArgs<ClassA>();
var classB = new ReturnArgs<ClassB>();
var xml = new ClassXml();
xml.Execute(classA);
var text = new ClassText();
text.Execute(classB);
Console.ReadKey();
}
public abstract class ClassBase
{
public void Execute(IReturnArgs<object> args)
{
// Do something common to both classes e.g. run tasks etc (not shown)
// calls print when completed, each call specific to child class.
Print(args);
}
/// <summary>
/// Abstract print method. Print invokes the child implementation.
/// </summary>
/// <param name="args"></param>
public virtual void Print(IReturnArgs<object> args){}
}
public class ClassXml : ClassBase
{
public void Execute(IReturnArgs<ClassA> args)
{
//invoked externally (Main) calling base common functionality.
base.Execute(args);
Print(args);
}
//print invoked by child class call - Note if invoked in this class then IReturnArgs<ClassA> could be used
//and a cast would not be necessary - however, this would separate common calls accross child classes.
public void Print(IReturnArgs<ClassA> args)
{
Console.WriteLine("ClassA Source {0}", ((IReturnArgs<ClassA>)args).Source.Xml);//ugly cast
}
}
public class ClassText : ClassBase
{
public void Execute(IReturnArgs<ClassB> args)
{
//invoked externally (Main) calling base common functionality.
base.Execute(args);
}
//print invoked by base class call which requires the cast IReturnArgs<ClassB> from IReturnArgs<object>
public override void Print(IReturnArgs<object> args)
{
Console.WriteLine("ClassB Source {0}", ((IReturnArgs<ClassB>)args).Source.Text);//ugly cast
}
}
}
}
爲什麼不使用通用接口/基類? –
在該示例中有一個名爲ClassBase的基類。我想要理解或解決的是如何在子類/父類之間傳遞ReturnArgs,讓它返回Source屬性的不同返回類型。 – Craig