【发布时间】:2011-10-19 10:53:16
【问题描述】:
这是有效的 C# 代码吗?
public class Product
{
[CompilerGenerated]
private string <Name>k__BackingField;
[CompilerGenerated]
private decimal <Price>k__BackingField;
public string Name
{
get;
private set;
}
public decimal Price
{
get;
private set;
}
public Product()
{
}
public static List<Product> GetSampleProducts()
{
List<Product> products = new List<Product>();
Product num1.Price = new decimal(1233, 0, 0, false, 2).Add(num1);
Product product1.Price = new decimal(1332, 0, 0, false, 2).Add(product1);
Product num2.Price = new decimal(2343, 0, 0, false, 2).Add(num2);
Product product2.Price = new decimal(2355, 0, 0, false, 2).Add(product2);
return products;
}
public override string ToString()
{
return string.Format("{0}: {1}", this.Name, this.Price);
}
}
上面的例子取自 JustDecompile(一个 .NET 反编译器),你可以在下面看到原始版本:
using System;
using System.Collections.Generic;
using System.Text;
namespace ProductV3
{
public class Product
{
public string Name { get; private set; }
public decimal Price { get; private set; }
public Product() { }
public static List<Product> GetSampleProducts()
{
return new List<Product>()
{
new Product() { Name = "ProductA", Price = 12.33M },
new Product() { Name = "ProductB", Price = 13.32M },
new Product() { Name = "ProductC", Price = 23.43M },
new Product() { Name = "ProductD", Price = 23.55M }
};
}
public override string ToString()
{
return string.Format("{0}: {1}", Name, Price);
}
}
}
我想知道第一个列表是反编译错误还是编译器生成的有效 C# 代码。我非常好奇 GetSampleProducts 方法中的代码是什么。
【问题讨论】:
-
产品名称哪里去了?
-
一个明显非法的部分由自动生成的标识符组成,其中包含 C# 不允许在标识符中使用的字符,但 CLR 允许。
-
你可以通过编译来判断它是否有效...
-
就像它所说的,只需将其通过编译器进行验证即可。至于它是否会做同样的事情,据我所知,我认为不会。就像 David Heffernan 说的那样,缺少产品名称,您也完全缺少第二个 2 示例产品。
标签: c# .net compiler-construction decompiler