0

非常によく似た2つの一般的な方法があります。1 つは明示的な戻り値の型で呼び出すことができ、もう 1 つは戻り値の型がobj提供されたものと同じであると推測できます。

最初のメソッドは次のように呼び出されます。RestResponse response = myCat.Put<RestResponse>()

//Perform a PUT on the current resource, returning the server response deserialized to a new object of the specified type.</summary>
//<typeparam name="T">The expected type of the resource post response. Use 'IRestResponse' to skip deserializing the request.</typeparam>
public static T Put<T>(this APIResource obj, List<Parameter> parameters = null)
{
    if (parameters == null) parameters = new List<Parameter>();
    parameters.Add(new Parameter() { Value = obj, Type = ParameterType.RequestBody });
    return RequestHelper<T>(obj.collection_name + "/" + obj.id, Method.PUT, parameters);
}

そして、自動のものはそのように呼ばれますCat response = myCat.Put();

//<typeparam name="O">(Automatically Inferred) The type of the current resource, which is also the expected type of the resource request response.</typeparam>
public static O Put<O>(this O obj, List<Parameter> parameters = null) 
     where O : APIResource 
{ return obj.Put<O>(parameters); } //I want to call the first method here.

これで、これらの定義がお互いにどのようにあいまいであるかがわかります。奇妙なことに、コンパイル エラーは発生しませんが、2 番目のメソッドが自分自身を呼び出すだけなので、実行時にスタック オーバーフローが発生します。

いずれかのメソッドの名前を変更せずに、2 番目のメソッドが最初のメソッドを呼び出すようにする方法はありますか?

4

2 に答える 2

2

2 つのメソッド (メソッド呼び出しが複数のシグネチャに一致する場合に行われる) の "より良い" を決定する場合、呼び出しポイントに "近い" と定義されているメソッドが優先されます。

より一般的な例の 2 つ:

  1. あるメソッドが同じ型で定義され、別のメソッドが定義されていない場合、その型のメソッドが優先されます。

  2. あるメソッドが同じ名前空間にあり、別のメソッドがそうでない場合、同じ名前空間にあるメソッドが優先されます。

あいまいさを解決する 1 つの方法は、それが拡張メソッドであるという事実を利用しないことです。そうでないかのように呼び出します (ただし、外部の呼び出し元が使用するための拡張メソッドにすることはできます)。

public static O Put<O>(this O obj, List<Parameter> parameters = null) 
     where O : APIResource 
{ return OtherPutClass.Put<O>(obj, parameters); }
于 2013-10-23T17:53:45.290 に答える
-1

正しい型に明示的にキャストしようとしましたか?

次のようになります。

public static O Put<out O>( this O obj , List<Parameter> parameters = null ) where O:APIResource
{
  return ((APIResource)obj).Put<O>(parameters) ;  //I want to call the first method here.
}

また

public static O Put<out O>( this O obj , List<Parameter> parameters = null ) where O:APIResource
{
  return .Put<O>( (APIResource)obj , parameters) ;  //I want to call the first method here.
}

私たちはあなたが望むものを手に入れます。

ただし、型システムがあなたの意図に関して混乱しているという事実は、バグを修正しようとしている誰かが混乱する可能性があることを示している可能性があります。

于 2013-10-23T18:02:24.543 に答える