C#中具有相同名称和签名但返回类型不同的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15362424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Method with same name and signature but different return type in C#
提问by Learner
I had an interview where I was asked the following:
我有一次面试,我被问到以下问题:
Question: A method with same name and signature but different return type. Is it possible and what is this type called he asked me.
问题:具有相同名称和签名但返回类型不同的方法。有没有可能,他问我这种类型叫什么。
Can someone please tell me the following:
有人可以告诉我以下内容:
Is above thing possible in any scenarios (Like one in base class and one in derived class atleast ?) If so what type is it ? Like compile or runtime polymorphism ?
In compile time polymorphism, what if the return types of methods are also different along with signature ? But only the name of function is same. Is it compile time polymorphism still ?
In overriding, what if I have different return type but the method name and signature are same ? Is it possible ? (He asked me this question, I answered wronglY :() Please help me.
上面的事情在任何情况下都是可能的(比如基类中的一个,派生类中的一个至少?)如果是这样,它是什么类型?像编译或运行时多态性?
在编译时多态中,如果方法的返回类型和签名也不同怎么办?但只有函数名称相同。它仍然是编译时多态性吗?
在覆盖中,如果我有不同的返回类型但方法名称和签名相同怎么办?是否可以 ?(他问我这个问题,我答错了 :() 请帮帮我。
Thank you
谢谢
采纳答案by Lee
It allows a method to return a more-derived type than the one declared in a base type e.g.
public interface ISomeInterface
{
object GetValue();
}
public class SomeClass : ISomeInterface
{
public string GetValue() { return "Hello world"; }
}
This is supported in Java but not in C#. The above will not compile since the return type of SomeClass.GetValue
is string
not object
.
Note that you cannot overload methods based on return-type alone i.e. the following is not valid:
public class SomeClass
{
public int GetValue() { return 1; }
public string GetValue() { return "abc"; }
}
You could do something similar using interfaces although you would need to implement them explicitly to disambiguate:
public interface IValue<T> { T GetValue(); }
public class SomeClass : IValue<int>, IValue<string>
{
string IValue<string>.GetValue() { return "abc"; }
int IValue<int>.GetValue() { return 1; }
}
它允许方法返回比基类型中声明的类型更派生的类型,例如
public interface ISomeInterface
{
object GetValue();
}
public class SomeClass : ISomeInterface
{
public string GetValue() { return "Hello world"; }
}
这在 Java 中受支持,但在 C# 中不受支持。上述将无法编译,因为的返回类型SomeClass.GetValue
是string
不是object
。
请注意,您不能仅基于返回类型重载方法,即以下内容无效:
public class SomeClass
{
public int GetValue() { return 1; }
public string GetValue() { return "abc"; }
}
您可以使用接口做类似的事情,尽管您需要明确地实现它们以消除歧义:
public interface IValue<T> { T GetValue(); }
public class SomeClass : IValue<int>, IValue<string>
{
string IValue<string>.GetValue() { return "abc"; }
int IValue<int>.GetValue() { return 1; }
}
If the names are the same but the parameters are different then this is method overloading. This is a form of polymorphism (ad-hoc polymorphism). Overloads are resolved statically at compile-type (unless you're using dynamic
in which case they are deferred to run-time).
You can overload on both the number of parameters and their type, so the following are all valid:
public void DoSomething(int value) { }
public void DoSomething(string value) { }
public void DoSomething(int value, string value) { }
Note that you can vary the return type of these methods - methods cannot only be overloaded based on their return type alone but they can differ if their parameter lists are different.
如果名称相同但参数不同,则这是方法重载。这是一种多态性(ad-hoc polymorphism)。重载是在编译类型静态解析的(除非你在使用dynamic
这种情况下它们被推迟到运行时)。
您可以重载参数的数量及其类型,因此以下都是有效的:
public void DoSomething(int value) { }
public void DoSomething(string value) { }
public void DoSomething(int value, string value) { }
请注意,您可以改变这些方法的返回类型 - 方法不能仅根据其返回类型进行重载,但如果它们的参数列表不同,则它们可能会有所不同。
Again this is return type covariance and is not supported in C#.
同样,这是返回类型协方差,在 C# 中不受支持。
回答by Todd Sprang
In C#, you cannot have methods like
在 C# 中,你不能有像
int Foo() { return 1; }
int Foo() { return 1; }
void Foo() { return; }
void Foo() { return; }
They must vary by more than return type.
它们的变化必须不止返回类型。
If the arguments are different, then you're good to go.
如果论点不同,那么你就可以开始了。
int Foo(string x) { return 1; }
int Foo(string x) { return 1; }
void Foo(double x) { return; }
void Foo(double x) { return; }
回答by Pieter Geerkens
Yes, it is possible to have multiple methods with the same signature but different return types, using Explicit Interface Implementation as shown here:
是的,使用显式接口实现,可以有多个具有相同签名但返回类型不同的方法,如下所示:
public interface I {
int foo();
}
public class C : I {
double foo() { return 2.0; }
int I.foo() { return 4; }
}
回答by Jean Hominal
Though return type covariance is not supported in C#, it is possible to emulate it by using explicit implementation and method hiding. That is a pattern which is used thoroughly in the ADO.NET APIs.
尽管 C# 不支持返回类型协方差,但可以通过使用显式实现和方法隐藏来模拟它。这是一种在 ADO.NET API 中被彻底使用的模式。
E.g.:
例如:
public interface ISomeValue {?}
public abstract class SomeValueBase : ISomeValue { }
public class SomeValueImpl : SomeValueBase { }
public interface ISomeObject { ISomeValue GetValue(); }
public abstract class SomeObjectBase : ISomeObject
{
ISomeValue ISomeObject.GetValue() { return GetValue(); }
public SomeValueBase GetValue() { return GetValueImpl(); }
protected abstract SomeValueBase GetValueImpl();
}
public class SomeObjectImpl : SomeObjectBase
{
protected override SomeValueBase GetValueImpl() { return GetValue(); }
public new SomeValueImpl GetValue() { return null; }
}
By doing that, the net result of calling GetValue()
is that it will always match the most specific available type.
通过这样做,调用的最终结果GetValue()
是它将始终匹配最具体的可用类型。
回答by gabnaim
Since this is an interview question, you can run with your answer a bit.
由于这是一个面试问题,您可以稍微回答一下。
Strictly speaking, a method with different return type and the same signature is not possible. However, broadly speaking, there are many ways of implementing a method whose concrete run time return type varies.
严格来说,具有不同返回类型和相同签名的方法是不可能的。但是,从广义上讲,有多种方法可以实现具体运行时返回类型各不相同的方法。
One is using generic parameters. Another is returning an interface or a super class with multiple implementations. Or, you can return an object, which can be cast to anything.
一种是使用泛型参数。另一个是返回具有多个实现的接口或超类。或者,您可以返回一个对象,该对象可以转换为任何内容。
As many mentioned, you can also use the "new" keyword to return a derived type of the same method in a subclass.
正如许多人提到的,您还可以使用“new”关键字返回子类中相同方法的派生类型。
回答by Marhazk
yes you can use the same method, same parameters (need to customize) and different return values.
是的,您可以使用相同的方法、相同的参数(需要自定义)和不同的返回值。
Just follow the codes below, it might help you.
只需按照以下代码进行操作,它可能会对您有所帮助。
public class myClass
{
public int myReturn() { return 123; }
public string myReturn(string temp = null) { return "test"; }
}
the thing is, it requires parameter to make execute the functions, but you still able to ignore the parameters since you have string temp = null
as optional parameters, which is you still call the functions with or without the parameters.
问题是,它需要参数来执行函数,但是您仍然可以忽略参数,因为您具有string temp = null
可选参数,即您仍然可以使用或不使用参数调用函数。
回答by Russell Bearden
I recently had this exact issue since I was parsing a config file with various types that all use a standard sort of config.Parse(string settingName) type interface.
我最近遇到了这个确切的问题,因为我正在解析具有各种类型的配置文件,这些类型都使用标准的 config.Parse(string settingName) 类型接口。
1st Solution Generic Method:
第一种解决方案通用方法:
T Parse<T> (string settingName)
{
T Result;
doParsing...
return T;
}
I didn't really like this since it involved explicitly specifying the type that's being used such as someSetting = Parse<float>("param");
我不太喜欢这个,因为它涉及明确指定正在使用的类型,例如 someSetting = Parse<float>("param");
So the solution I used is redundant but much more clean in my opinion:
所以我使用的解决方案是多余的,但在我看来更干净:
T Parse<T> (string settingName, out T result)
{
doParsing...
return T;
}
The out variable and the return are identical so it's a bit redundant but it enables what I think is a much cleaner interface:
out 变量和 return 是相同的,所以它有点多余,但它启用了我认为更清晰的界面:
setting = Parse("intparam", out setting);
And you get methods that vary only by return type for a slight cost of redundancy. On top of that if the type of your data changes, for instance from a double to a float, then you everything will continue working just fine, whereas with the first solution you'd end up getting cannot implicitly convert errors.
并且您会获得仅因返回类型而异的方法,但会产生轻微的冗余成本。最重要的是,如果您的数据类型发生变化,例如从双精度数变为浮点数,那么您的一切都将继续正常工作,而使用第一个解决方案您最终得到的解决方案无法隐式转换错误。
回答by topik
You can do it whit interface
你可以用界面来做
public interface IMyInterface
{
int Metoda1()enter code here`;
}
public class MyClass : test.IMyInterface
{
public IMyInterface Metoda1()
{
return new MyClas();
}
int test.IMyInterface.Metoda1()
{
return 1;
}
}
static void Main(string[] args)
{
MyClass instance = new MyClass();
IMyInterface inst = instance.Metoda1();
/* IMyInterface ints2 = inst.Metoda1(); //will not compile*/
Console.WriteLine(inst.GetType().ToString()); ;
object inst3 = inst.Metoda1();
Console.WriteLine(inst3.GetType().ToString());
}
回答by Thomas
You can use a dynamic
return type:
您可以使用dynamic
返回类型: