Access C# anonymous type object returned from a method [closed]

大憨熊 提交于 2020-01-25 03:50:54

问题


Someone wrote a method that returns an object type.

public object GetProvider(double personId)
{
    // Some other code here

    return new {
       FirstName = Convert.ToString(reader["FirstName"]),
       LastName = Convert.ToString(reader["LastName"])
    };
}

In different part of code, we use this library method.

var d = GetProvider(123); 
string fName = d.GetType().GetProperty("FirstName").GetValue(d, null).ToString();

How can I improve this code or simplify it? I guess they should have created a class and returned an object of it instead of object type. Also, I have seen code that use dynamic in C#4. I tried that, but it didn't work well with object type. Any thoughts?


回答1:


Implement dynamic like this:

dynamic d = GetProvider(123);

string fName = d.FirstName;


It seems that this part is actually irrelevant to the original post, as the OP has no control over the method's return-type. I'm leaving it here because it's still best-practice and should be followed in a significant majority of cases, and in an ideal world, the writer of the original method would read this and change his or her ways.

But in general, I'd be tempted to just make a type. It's not like it takes all that much effort to spin up a class to do exactly what you want.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Then you can have everything strong-typed and you don't need to use dynamic. I don't think I've ever found a truly appropriate use for dynamic. It's nice because it's quick and easy to write, but it tends to just cause problems in the long run in 99% of real-world uses. I'm not saying it should be abolished because that 1% is useful (I'm thinking serialization of dynamic data here, but even there I usually just use the string indexer properties), but generally speaking, think twice before using it and make sure there isn't a better solution. Anonymous types are useful in LINQ queries where it's all in-scope and compiled, but I wouldn't change scopes using them unless you absolutely have to, and you pretty well never do.




回答2:


If this were me, I would probably wrap the result from GetProvider in a strongly typed class. The class below takes the response from GetProvider as an argument on its constructor.

public class Provider
{
    public Provider(object provider)
    {
        dynamic dynamicProvider = provider;
        this.FirstName = dynamicProvider.FirstName;
        this.LastName = dynamicProvider.LastName;
    }

    public string FirstName { get; set; }
    public string LastName { get; set; }
}

Then just replace

var d = GetProvider(123);

with

var d = new Provider(GetProvider(123));


来源:https://stackoverflow.com/questions/25068965/access-c-sharp-anonymous-type-object-returned-from-a-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!