c#.net创建一个简单的匿名对象并将其转换为类类型

发布于 2025-02-08 02:41:46 字数 778 浏览 3 评论 0原文

也许我还不够聪明,但是...

我有一个刚创建的匿名物体,想把它扔到一个特殊的班级上。


我尝试了类似:

  • ()convert:someclass casted =(className)obj
  • 作为类型:someclass casted = obj as className className

最后一个想法i i在网上发现的是通过每个物业进行投射: https://dotnetfiddle.net/bu8gwe 对象)),

但无效。 :(


这是我的对象:

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

,这是我的类型,它是一个自己的类:

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

因此如何在类型someclass中施放obj

我为每个建议感到高兴。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

若水般的淡然安静女子 2025-02-15 02:41:46

我明白了: https://dotnetfiddle.net/nvxchr

,它不是fieldinfo正如我说的。

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

好的,反射很昂贵,所以我首先试图询问类型是否正确,只有在不使用上面的每个示例的情况下,我才会使用。

但是,可以在类(类型)中施放匿名对象。

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).

睫毛上残留的泪 2025-02-15 02:41:46

首先,主要是一般建议:请勿在中使用空的捕获条款 - catch constructs constructs(除了所谓的 vexing异常,但是我离题了)。如果您尽最大的努力忽略并丢弃任何例外,您的代码抛出了看不见,您将很难知道代码出了什么问题。

如果您要打印出任何捕获的例外,而不是默默丢弃它,则例外将告诉您代码出了什么问题(即,在代码中需要解决什么)。

无论如何,使用此行:

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

您正在尝试从 codeRecord class( tmp )获得属性信息。现在,查看您的 CodeRecord 类。 codeRecord 中没有定义的属性,只有字段。如果要通过反思中的 codeRecord 中的字段填充字段,则需要获得fieldinfo而不是property> property> property> propertyinfo

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

一些无关的观察:

什么heck是activator.createinstance(type.getType(typeof(t).toString())) ???您具有 t 的类型对象,通过typeof(t)。然后,您可以获得其名称字符串。使用其名称字符串,您尝试再次找到 t 的类型对象,您已经使用了typeof(t)。我不知道那是什么,但是我认为您需要一些睡眠; P您只能使用activator.CreateinStance(typeof(t))。好吧,请抓住,我将其拿回来,您可以使用activator.createinstance&lt; t&gt;()

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 (i.e., 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>().

终难遇 2025-02-15 02:41:46

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

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

Maybe the situation is more "dynamic" than I realize, but why not just:

SomeClass casted = new SomeClass { FieldOne = test.FieldOne, FieldTwo = test.FieldTwo, };
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文