我通常覆盖ToString()方法以输出属性名称和与之关联的值.我有点厌倦了手工编写这些,所以我正在寻找一个动态的解决方案.
主要:
TestingClass tc = new TestingClass()
{
Prop1 = "blah1",
Prop2 = "blah2"
};
Console.WriteLine(tc.ToString());
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
TestingClass:
public class TestingClass
{
public string Prop1 { get; set; }//properties
public string Prop2 { get; set; }
public void Method1(string a) { }//method
public TestingClass() { }//const
public override string ToString()
{
StringBuilder sb = new StringBuilder();
foreach (Type type in System.Reflection.Assembly.GetExecutingAssembly().GetTypes())
{
foreach (System.Reflection.PropertyInfo property in type.GetProperties())
{
sb.Append(property.Name);
sb.Append(": ");
sb.Append(this.GetType().GetProperty(property.Name).Name);
sb.Append(System.Environment.NewLine);
}
}
return sb.ToString();
}
}
Run Code Online (Sandbox Code Playgroud)
目前输出: …
var doc3 = XDocument.Load(@"C:\Projects\ScanBandConfigTesting\ScanBandConfigTesting\ScanBandConfigSmall.xml");
var scanBand = new ScanBand()
{
ListOfForms = (from form in doc3.Descendants("form")
select new ScanBandForm()
{
FormTypes = form.Attribute("types").Value,
ScanBandNumber = form.Attribute("number").Value,
ListOfRows = (from row in form.Descendants("row")
select new ScanBandRow()
{
AllowSpaces = row.Element("allowSpaces").Value.ToLower() == "true",
SplitCharacter = row.Element("splitCharacter").Value,
ListOfColumns = (from column in row.Descendants("column")
select new ScanBandColumn()
{
AlwaysKey = column.Element("allwaysKey").IsEmpty ? false : column.Element("allwaysKey").Value.ToLower() == "true",
DataTypeString = column.Element("dataType").IsEmpty ? string.Empty : column.Element("dataType").Value,
MatchingFieldName = column.Element("matchingFieldName").IsEmpty ? string.Empty : column.Element("matchingFieldName").Value,
NonField = column.Element("nonField").IsEmpty …Run Code Online (Sandbox Code Playgroud) public class EcImageWrapper
{
//etc...
public IQueryable<EcFieldWrapper> ListOfFields
{
get
{
//logic here
return this.listOfFields.AsQueryable();
}
}
public EcFieldWrapper FindBy(Expression<Func<EcFieldWrapper, int, bool>> predicate)
{
return this.ListOfFields.Where(predicate).SingleOrDefault();
}
public EcFieldWrapper FindByName(string fieldName)
{
return this.FindBy(x => x.Name.ToUpper() == fieldName.ToUpper());
//error here, wanting 3 arguments
//which makes sense as the above Expression has 3
//but i don't know how to get around this
}
Run Code Online (Sandbox Code Playgroud)
由于某种原因,表达式>要求我使用3个参数,在过去我只使用2作为有问题的实例.但是,现在我想在这个实例中对一个集合进行查找.
我收到以下错误:
Delegate 'System.Func<MSDORCaptureUE.Wrappers.EcFieldWrapper,int,bool>' does not take 1 arguments
The best overloaded method match for 'CaptureUE.Wrappers.EcImageWrapper.FindBy(System.Linq.Expressions.Expression<System.Func<CaptureUE.Wrappers.EcFieldWrapper,int,bool>>)' has some …Run Code Online (Sandbox Code Playgroud)