重载变量类型? [英] Overloaded variable type?

查看:80
本文介绍了重载变量类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





是否可以使用同名的变量,可以是字符串,也可以是包含字符串的对象?



例如:



Hi,

Is it possible have a variable with the same name that can either be a string or an object that contains a string?

For example:

public mynameobj
{
  value: string { get; set; }
}

public string myName { get; set; }
public mynameobj myName { get; set; } // overload somehow, so that either works?





我试了一下,我不能想出任何东西。



想要做的原因这是因为使用JSON.net反序列化时,被提供给我的数据有时是一个字符串,有时候是一个带有字符串的对象。所以我收到错误类型的错误,我找不到解决它的方法。



例如:



input1:{cInfo:{myName:some value}}

vs.

input2:{cInfo: {myName:{value:}}}





I tried searching a bit and I can''t come up with anything.

The reason for wanting to do this is because with JSON.net deserializing, the data that''s being fed to me is sometimes a string and sometimes an object with a string in it. So I get an error for wrong type and I can''t find a way to work around it.

An example:

input1: {"cInfo":{"myName":"some value"}}
vs.
input2: {"cInfo":{"myName":{"value":""}}}

public class info
{
   public string myName { get; set; }
}

public class myResult
{
  public info cInfo { get; set; }
}

...

public class someMethod()
{
	Newtonsoft.Json.JsonSerializerSettings jsonSettings = new Newtonsoft.Json.JsonSerializerSettings();
        jsonSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
        jsonSettings.DefaultValueHandling = DefaultValueHandling.Ignore;

        myResult result = JsonConvert.DeserializeObject(json, jsonSettings);

//with input2, you get: Error reading string. Unexpected token: StartObject. Path 'cInfo.myName', line #, position #.  because it's trying to read an object as string

	string something = result.cInfo.myName; // 
}

推荐答案

可能不是最优雅的,但它是一个有效的解决方案:



Might not be the most elegant one, but it is a working solution:

using System;
using Newtonsoft.Json;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Newtonsoft.Json.JsonSerializerSettings jsonSettings = new Newtonsoft.Json.JsonSerializerSettings();
            jsonSettings.MissingMemberHandling = Newtonsoft.Json.MissingMemberHandling.Ignore;
            jsonSettings.DefaultValueHandling = DefaultValueHandling.Ignore;

            dynamic result1 = JsonConvert.DeserializeObject(@"{""cInfo"":{""myName"":""some value""}}", jsonSettings);
            dynamic result2 = JsonConvert.DeserializeObject(@"{""cInfo"":{""myName"":{""value"":""another value""}}}", jsonSettings);

            Console.WriteLine("{0}\n{1}",result1.cInfo.myName, result2.cInfo.myName.value);
        }
    }
}


完全没有意义。



除了丑陋且非常令人困惑的术语和一些神话外,没有超载之类的东西。 (很多初学者都感到困惑!可以在CodeProject上观察到。)方法被重载,因为没有任何重载。它们只是具有相同名称的不同方法,没有别的。调用代码只能编译,因为在许多(并非所有)情况下,编译器可以通过实际参数的数量和类型确定调用哪一个。如何处理相同名称和界面的属性?当您调用(读取或写入)属性时,编译器如何确定使用哪个成员?



您的问题就是您提出问题的方式。也许有一个非常有趣的问题可能有一个很好的解决方案,但好的事情在你的问题中陷入沉沦,因为你太过于专注于一些误解。你开始解释目的,这是你应该付出更多努力的地方。详细解释目的,然后你就可以获得更好的建议。







实际上,看起来一个非常相似的问题已经解决了。在数据合同中。请参阅:

http://msdn.microsoft.com/en-us /library/ms733127.aspx [ ^ ]。



请了解它的工作原理,它会给你一些好主意。学到了?现在,请注意属性 [DataMember] Name 属性(命名参数)。看起来有点熟悉,不是吗?







顺便说一下,也可以使用基于数据合同的JSON序列化。这里:

http:// msdn。 microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx [ ^ ]。



你不觉得吗?你的问题已经解决了吗?



-SA
Makes no sense at all.

There is no such thing as "overloading", except ugly and very confusing terminology and some myths. (So many beginner have been confused! It''s can be observed on CodeProject.) Methods are "overloaded" because nothing is overloaded. They are just different methods with identical names, nothing else. The calling code can compile just because in many (not all) cases a compiler can figure out which one to call by the number and types of actual parameters. And what to do with the properties of identical name and interface? How the compiler can figure out which member to use when you call (read or write) the property?

Your problem is the way you ask the question. Maybe there is a really interesting problem which may have a good solution, but good thing is sunken in your question because you are too much preoccupied with some misconception. You started to explain the purpose, and this is where you should put more effort. Explain the purpose as well as you can, in detail, then you can get a chance for much better advice.



Actually, it looks like a very similar problem is already solved. In Data Contract. Please see:
http://msdn.microsoft.com/en-us/library/ms733127.aspx[^].

Please learn how it works, it will give you some good ideas. Learned? Now, pay attention for the Name property (named parameter) of the attribute [DataMember]. Looks somewhat familiar, isn''t it?



By the way, JSON serialization based on Data Contract is also available. Here:
http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx[^].

Don''t you think your problem is already solved?

—SA


我最终做了类似的事情: br />


I ended up doing something like:

public dynamic myName { get; set; }

if (myName != null)
  if (myName is string)
     // can access it directly
  else
    // is object with .value property for reading 
    // (need more checks for safety, of course)





这个想法是从ZoltánZörgő产生的,所以谢谢。



还有谢尔盖亚历山德罗维奇的详细信息它不是''超载''

我同意,尤其是它们只是名字相同的不同方法,没有别的。 - 所以我会开始称之为。 />
T.他的DataContract信息也很有用,但是我想找到一种方法来实现它,而不是改变太多代码,这是我实现的(即使它不理想?)



This idea was spawned from Zoltán Zörgő, so thank you.

And also Sergey Alexandrovich for the detailed information about how it''s not an ''overload''
I agree, especially with "They are just different methods with identical names, nothing else. " -- so I will start calling it that.
The DataContract info was also useful, but I wanted to find a way to do it without changing too much code, which I achieved (even if it''s not ideal?)


这篇关于重载变量类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆