从对象中提取价值的最佳实践是什么?
从对象中提取属性以便我们获取其值的最佳实践是什么?
我们有以下代码结构:
public List<Group> Activities { get; set; }
在 Group 中,我们有:
public List<Span> Spans { get; set; }
在 Span 类中,我们有:
public object Activity { get; set; }
在方法中,我有以下循环,我想从 TV 的对象 Activity 属性 Id 中获取:
foreach (var activity in result.Activities)
{
if (activity.Spans != null)
{
foreach (var span in activity.Spans)
{
if (span.Activity != null)
{
foreach (var propertyInfo in typeof(Spans).GetProperties())
{
if (propertyInfo.Name == "Activity")
{
//take value from activity
}
}
}
}
}
}
在 span.Activity 中,我们有: { Time = 123, EndTime = 123,Points = [ -48, -49 ],PointsStart = [ 0, -2, ],TV = [ { "time": "123", "Id": 7, "TitleId": 5 } ] }
我需要从 TV 获取 Id 属性值,然后将其添加到列表中。 最好的做法是什么以及如何做?
Which is the best practice for extracting property from object ,so that we can take its value?
We have the following code structure:
public List<Group> Activities { get; set; }
In Group we have:
public List<Span> Spans { get; set; }
In Span class we have:
public object Activity { get; set; }
In method I have the following loop that I want to take from object Activity property Id from TV:
foreach (var activity in result.Activities)
{
if (activity.Spans != null)
{
foreach (var span in activity.Spans)
{
if (span.Activity != null)
{
foreach (var propertyInfo in typeof(Spans).GetProperties())
{
if (propertyInfo.Name == "Activity")
{
//take value from activity
}
}
}
}
}
}
In span.Activity we have : { Time = 123, EndTime = 123, Points = [ -48, -49 ], PointsStart = [ 0, -2, ], TV = [ { "time": "123", "Id": 7, "TitleId": 5 } ] }
I need to take from TV the Id property value and add it later to a list.
Which is the best practice to do it and how?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这可能不是最佳实践,但您可以使用反射。
您可以使用 EgonsoftHU.Extensions.Bcl nuget 包,其中包含
GetPropertyValue()
使用反射的扩展方法:It may not be the best practise but you can use reflection.
You can use the EgonsoftHU.Extensions.Bcl nuget package that contains a
GetPropertyValue()
extension method that uses reflection:由于跨度内的活动是未知并且对象类型是未知,因此我们必须使用REGEX之类的东西来匹配我们的值。
这是完美运行的东西。
让我知道它是否适合您:)
Since Activity inside span is an unknown and the object type is unknown, we'll have to use something like REGEX to match our values.
Here's something that works perfectly.
Let me know if it works for you :)