[英]How to call a method in another class from a generic method?
为什么标有//Dont work in the bottom of the code
的行在//Dont work in the bottom of the code
无法编译?
我想在不同的类中重用WriteMessage
方法,我尝试使用generics
,但是我不确定如何使用它。
class ClassOne
{
public string MethodOne()
{
return ("ClassOne");
}
public string MethodTwo()
{
return ("ClassOne -MethodTwo ");
}
}
class ClassTwo
{
public string MethodOne()
{
return ("ClassTwo");
}
public string MethodTwo()
{
return ("ClassOne -MethodTwo ");
}
}
class Program
{
private static void Main()
{
var objectOne = new ClassOne();
WriteMessage(objectOne);
var objectTwo = new ClassTwo();
WriteMessage(objectTwo);
Console.ReadKey();
}
public static void WriteMessage<T>(T objectA)
{
var text = objectA.MethodTwo(); //Dont Work
Console.WriteLine("Text:{0}", text);
}
}
尝试实现一个接口:
范例:
public interface IHasTwoMethods
{
string MethodOne()
string MethodTwo()
}
在您的课程上实现此接口:
class ClassOne : IHasTwoMethods
class ClassTwo : IHasTwoMethods
然后在您的通用方法中执行以下操作:
public static void WriteMessage<T>(T objectA) where T : IHasTwoMethods
{
var text = objectA.MethodTwo(); //Will work
Console.WriteLine("Text:{0}", text);
}
您可以在此处阅读有关接口的更多信息: http : //msdn.microsoft.com/zh-cn/library/87d83y5b.aspx
这不会编译,因为就编译器而言, objectA
只是一个Object
。
为了使它起作用,您需要使用通用类型约束 :
public interface MyInterface
{
string MethodTwo();
}
public class A : MyInterface
{
...
}
public class B : MyInterface
{
...
}
public static void WriteMessage<T>(T objectA) where T: MyInterface
{
var text = objectA.MethodTwo(); //Will Work!
Console.WriteLine("Text:{0}", text);
}
MSDN: 类型参数的约束
由于您要使用T
传递通用类型的对象,因此编译器不知道您使用的是什么类-就其所知,它可能是int
或Application
或其他任何东西。
您可能想要的是让ClassOne
和ClassTwo
继承自另一个类,该类具有一个同时实现的抽象MethodTwo
类。 就像是...
abstract class SuperClass
{
public abstract string MethodOne();
}
class ClassOne : SuperClass
{
public override string MethodOne()
{
return ("ClassOne");
}
}
然后在Main:
public static void WriteMessage<T>(T objectA) where T : SuperClass
{
var text = objectA.MethodOne();
Console.WriteLine("Text:{0}", text);
}
在此处阅读有关C#继承的信息: http : //msdn.microsoft.com/zh-cn/library/ms173149.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.