简体   繁体   中英

c#.net create a simple anonymous object and convert it to class type

maybe I'm not clever enough, but...

I have a freshly created anonymous object and wanna cast it to a special class.


I tried something like:

  • () convert: SomeClass casted = (ClassName) obj
  • as type: SomeClass casted = obj as ClassName

The last idea I found online was to cast via each property: https://dotnetfiddle.net/bU8gwE (by method: CastTo<T>(object) )

But nothing worked. :(


Here is my object:

var test = new { FieldOne = "test2", FieldTwo = 2 };

And here is my type, it's an own class:

public class SomeClass
{
    public string FieldOne;
    public int FieldTwo;
}

So how to cast obj in type SomeClass ?

I'm happy for every advise.

First and primarily, a general advice: do not use empty catch clauses in your try - catch constructs (with the exception of so-called vexing exceptions , but i digress). If you try your hardest to ignore and discard any exception your code throws unseen, you will have a very hard time knowing what's going wrong with your code.

If you were to print out any caught exception instead of silently discarding it, the exception would tell you what is going wrong with your code (ie, what needs to be fixed in your code).

Anyways, with this line:

tmp.GetType().GetProperty(pi.Name).SetValue(...)

you are trying to obtain a property info from your CodeRecord class ( tmp is an instance of CodeRecord ). Now, look at your CodeRecord class. There are no properties defined in CodeRecord , only fields. If you want to populate the fields in CodeRecord through reflection, you will need to get a FieldInfo and not a PropertyInfo :

tmp.GetType().GetField(pi.Name).SetValue(tmp, pi.GetValue(obj, null));

Some unrelated observation:

What the heck is Activator.CreateInstance(Type.GetType(typeof(T).ToString())) ??? You have the type object for T via typeof(T) . You then get its name string. With its name string you try to find the type object of T again which you already had with typeof(T) . I don't know what that is, but me thinks you need some sleep ;-P You could just have used Activator.CreateInstance(typeof(T)) . Well, hold on, i take that back, you could just have used Activator.CreateInstance<T>() .

I got it: https://dotnetfiddle.net/nvxchR

And it was not FieldInfo, it was PropertyInfo, exactly as I said.

var tmp = new CodeRecord();
(obj.GetType()).GetProperties().ToList().ForEach(prop =>
    tmp.GetType().GetField(prop.Name).SetValue(tmp, prop.GetValue(obj, null)));
return tmp;

Okay, the reflections are expensive, so I first try to ask if type is right and only if not I use the for each sample above.

But so it's possible to cast an anonymous object in a class (type).

也许情况比我意识到的更“动态”,但为什么不只是:

SomeClass casted = new SomeClass { FieldOne = test.FieldOne, FieldTwo = test.FieldTwo, };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM