【发布时间】:2015-02-21 20:13:09
【问题描述】:
下午好,
我不太确定如何表达我的问题,所以请原谅任何不相关的内容,如果我遗漏了任何重要的内容,请告诉我!我对 lambdas、regex 和 linq 也没有经验,所以请指出我做得不好/可能会做得更好的任何事情。
我的问题是:我可以得到一个类的引用,而我只知道一个属性吗?具体来说,在下面的代码 sn-p 中,我想将 propertyValues[0] 中的 0 的索引更改为存储在同一类上的变量。有没有类似this 的东西访问父级?
有关更多上下文,我在下面粘贴了相关的修剪代码。
return Regex.Replace ( originalString, "{(.*?)}", match =>
User.user.properties.First( property =>
property.id == match.ToString ().Substring ( 1, match.ToString ().Length - 2 ))
.propertyValues[0].adjectives[0]);
public class Property
{
public string id;
public List<Value> propertyValues = new List<Value> ();
public sbyte propertyIndex;
}
感谢您抽出宝贵时间阅读本文!
编辑
感谢您的反馈,Philip Stuyck 我会尽力解释得更好。
我正在寻找一种方法来获取对属性的父类的引用,或者一种在 lambda 表达式中创建局部变量的方法。为了说明,我有以下类和返回方法。
属性类,
public class Property
{
public string id;
public List<Value> propertyValues = new List<Value> ();
public sbyte propertyIndex;
}
用户类,
public class User
{
public static User user = new User ();
internal List<Property> properties = new List<Property> ();
}
GetVariable 方法,
public static class GetVariable
{
public static string FromUser ( string originalString )
{
return Regex.Replace ( originalString, "{(.*?)}", match => User.user.properties.First ( property => property.id == match.ToString ().Substring ( 1, match.ToString ().Length - 2 )).propertyValues[0].adjectives[0]);
}
}
GetVariable.FromUser 方法应返回一个新字符串,该字符串已用来自User.user.properties 的字符串替换了括在括号中的子字符串的每个实例。因此,它可以传递“这是一个 {Example}。”,并返回“这是一个 Demo”(如果 User 类有一个 id 为 Example 的属性,并且值为 Demo)。
我的问题是与 GetVariable 方法有关,更具体地说,是最后一部分:propertyValues[0]。我希望索引(当前为 0)成为 Property 类上的变量,User.user.properties.First 委托正在查找该变量。
因此,理想情况下,它会像 User.user.properties.First ( property => property.id == match.ToString ()).propertyValues[property.propertyIndex] 一样简单,但我无法访问括号外的属性。
我希望这有助于解释它,尽管我觉得它仍然太复杂了。如果我能想到更好的方式来表达我的问题,我会这样做。另外,我很乐意通过评论澄清任何事情。
【问题讨论】:
-
完全不明白你的意思。请完全改写。
-
@PhilipStuyck 感谢您的评论!我试图改写我的问题,我希望现在更清楚了。我不太擅长解释这类问题,所以请早点原谅我的糟糕工作。如果还是太模糊,请在 cmets 中询问,这样我可以尝试使其更清楚一点。再次感谢!