假设我有这样的代码:
interface IObject
{
IObject GetSomeObject();
}
public class ObjectClass : IObject
{
IObject GetSomeObject()
{
// method implementation here
}
}
有没有办法,我使GetSomeObject()
类ObjectClass
方法返回ObjectClass
,没有IObject
?
我知道我可以这样使用它:
ObjectClass object1= someObject1.GetSomeObject() as ObjectClass;
但我想要达到的目标是:
public class ObjectClass : IObject
{
ObjectClass GetSomeObject()
{
// method implementation here
}
}
这样可能吗?
答案 0 :(得分:6)
您可以使用泛型:
interface IObject<T> where T : IObject<T>
{
T GetSomeObject();
}
public class ObjectClass : IObject<ObjectClass> { ... }
答案 1 :(得分:4)
您可以使用explicit interface implementation:
public interface IObject
{
IObject GetSomeObject();
}
public class ObjectClass : IObject
{
public ObjectClass GetSomeObject()
{
return this;
}
IObject IObject.GetSomeObject()
{
return this;
}
}
这样,访问ObjectClass
的消费者可以呼叫ObjectClass GetSomeObject()
,而通过IObject
访问此类实例的消费者只能呼叫IObject GetSomeObject()
。
答案 2 :(得分:1)
您可以使用泛型:
interface IObjectReturnable<T>
{
T GetSomeObject();
}
public class ObjectClassRet : IObjectReturnable<ObjectClassRet>
{
public ObjectClassRet GetSomeObject()
{
// method implementation here
return new ObjectClassRet();
}
}