gpt4 book ai didi

单个对象的 C# 数据转换

转载 作者:行者123 更新时间:2023-11-30 21:28:36 24 4
gpt4 key购买 nike

我想知道是否有一种方法可以在一行中将方法结果转换为新对象,这在使用 List、Linq 和 Lambda 表达式时是可能的。

使用列表的例子:

List<int> ints = GetListOfInts();
List<anotherClass> = ints.Select(x => new anotherClass(){ memberVariable = x }).ToList();

通过这个,我可以将类型 A 的列表映射到类型 B 的列表。

我想对单个对象执行此操作,而不是列表。这就是我的意图:

// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = (GetObjectA() x => new ObjectB(){ memberVariable = x });

这只是伪代码,我知道它不会编译或工作。这种类型的转换目前在 C# 中是否可行?

我知道我可以使用映射器、自定义方法等,但我想知道是否可以通过 lamba 表达式来实现,就像列表一样。

最佳答案

// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = new[]{ GetObjectA() }.Select(x => new ObjectB(){ memberVariable = x }).First();

不太好,但应该可以。

但是,如果它真的是特定代码,您可以这样做

ObjectB objectB = new ObjectB(){ memberVariable = GetObjectA() };

如果你想把它封装得很好,你可以这样写:

public static class ObjectExtensions
{
public static TOutput Transform<TInput, TOutput>(this TInput input, Func<TInput, TOutput> transform)
{
return transform(input);
}
}

然后像那样使用它:

// GetObjectA returns an instance of ObjectA
ObjectA objectA = GetObjectA();

// Here, GetOjbectA's result is mapped to an instance of ObjectB
ObjectB objectB = GetObjectA().Transform(x => new ObjectB(){ memberVariable = x });

关于单个对象的 C# 数据转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56259991/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com