方法之间的调用模棱两可

本文关键字:模棱两可 调用 之间 方法 | 更新日期: 2023-09-27 18:19:12

我尝试在活动之间传递数据并出现错误:

C:'Users'nemesis'Documents'GitHub'Murakami_kiev'MurakamiKiev'Menu Activities'SoupesActivity.cs(5,5):错误CS0121:调用在以下方法或属性之间是模糊的:PutExtra(string, short)'和'Android.Content.Intent '。PutExtra(string, bool)' (CS0121) (MurakamiKiev)

活动1中的代码:

private void ParseAndDisplay1(JsonValue json) {
    TextView productname = FindViewById<TextView> (Resource.Id.posttittle);
    TextView price = FindViewById<TextView> (Resource.Id.price);
    TextView weight = FindViewById<TextView> (Resource.Id.weight);
    productname.Click += delegate {
        var intent404 = new Intent (this, typeof(SoupesDetailActivity1));
        JsonValue firstitem = json [81];
        intent404.PutExtra ("title", firstitem ["post_title"]);
        intent404.PutExtra ("price", firstitem ["price"] + " грн");
        intent404.PutExtra ("weight", firstitem ["weight"] + "г");
        StartActivity (intent404);
    };
}

Activity2中接收属性时的代码:

private void ParseAndDisplay(JsonValue json) {
    TextView productname = FindViewById<TextView>(Resource.Id.posttitle);
    TextView content = FindViewById<TextView>(Resource.Id.postcontent);
    TextView price = FindViewById<TextView>(Resource.Id.price);
    TextView weight = FindViewById<TextView>(Resource.Id.weight);
    //JsonValue firstitem = json[81];
    productname.Text = Intent.GetStringExtra("title");
    content.Text = firstitem["post_excerpt"];
    price.Text = firstitem["price"] + " грн";
    weight.Text = firstitem["weight"] + "г";
}

代码出了什么问题?

谢谢你的帮助

方法之间的调用模棱两可

JsonValue继承自object,当你调用intent404.PutExtra时,.NET不知道他将调用哪个方法,为了解决你的问题,你只需要强制转换对象,像这样:

intent404.PutExtra("title", (string)firstitem["post_title"]);

intent404.PutExtra("title", Convert.ToString(firstitem["post_title"]));

MSDN上的Json值:

https://msdn.microsoft.com/en-us/library/system.json.jsonvalue (v = vs.95) . aspx

我想这会解决你的问题。

发生此错误是因为编译器没有指定足够的数据来理解调用哪个方法。
要解析任务,必须在PutExtra方法调用中显式指定变量类型:

intent404.PutExtra ("title", (firstitem ["post_title"]).ToString());
intent404.PutExtra ("price", (firstitem ["price"] + " грн").ToString());
intent404.PutExtra ("weight", (firstitem ["weight"] + "г").ToString());

前面的答案显示了如何解决这个问题,但是错误消息令人困惑,所以我将描述它是如何发生的。

考虑以下方法

private static void Bar(short value) { }
private static void Bar(bool value) { }

编译器应该根据参数类型决定运行哪个方法。

编译器将选择第一个方法:

short s = 0;
Bar(s);

编译器将选择第二个方法:

bool b = true;
Bar(b);

如果编译器找不到适合你的参数类型的方法,它会给你一个错误:

object obj = new object();
Bar(obj);

不能从'object'转换为'short'

并且您尝试将firstitem ["post_title"]作为方法参数传递。这个参数的类型是JsonValue。出现ambiguous call错误的原因是JsonValue有隐式强制转换操作符。

考虑以下类:

public class Foo
{
    public static implicit operator short (Foo value)
    {
        return 0;
    }
    public static implicit operator bool (Foo value)
    {
        return false;
    }
}

编译器在选择合适的方法时,可以将该类视为FooObjectshortbool。这就是为什么你会得到一个错误

调用在以下方法或属性之间是二义性的:'Bar(object)'和'Bar(short)'

Foo f = new Foo();
Bar(f);