我正在尝试在运行时生成一些代码,我在其中添加了一些样板,并且允许用户输入实际的工作代码.我的样板代码看起来像这样:
using System;
public class ClassName
{
public double TheFunction(double input)
{
// user entered code here
}
}
Run Code Online (Sandbox Code Playgroud)
理想情况下,我想我想使用string.Format插入用户代码并创建一个唯一的类名,但我在格式字符串上得到一个例外,除非它看起来像这样:
string formatString = @"
using System;
public class ClassName
{0}
public double TheFunction(double input)
{0}
{2}
{1}
{1}";
Run Code Online (Sandbox Code Playgroud)
然后我像这样调用string.Format:
string entireClass = string.Format(formatString, "{", "}", userInput);
Run Code Online (Sandbox Code Playgroud)
这很好,我可以处理在格式字符串中使用{0}和{1}代替我的花括号的丑陋,除了现在我的用户输入也不能使用花括号.有没有办法在我的格式字符串中转义大括号,或者将用户代码中的花括号转换为{0}和{1}的好方法?
顺便说一句,我知道这种事情是一个等待发生的安全问题,但这是一个Windows Forms应用程序,供内部使用在未连接到网络的系统上,因此在这种情况下风险是可以接受的.
我正在使用LINQ to objects并且有一个函数,在某些情况下我需要在调用之前修改底层集合Aggregate(...),然后在函数返回结果之前将其返回到其原始状态Aggregate(...).我当前的代码看起来像这样:
bool collectionModified = false;
if(collectionNeedsModification)
{
modifyCollection();
collectionModified = true;
}
var aggregationResult = from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue;
if(collectionModified)
modifyCollection();
return aggregationResult;
Run Code Online (Sandbox Code Playgroud)
但是,如上所述,如果我修改了集合,我将得到错误的结果,因为我在aggregationResult枚举之前将集合恢复到其原始状态,并且LINQ结果是惰性评估的.我目前的解决方案是使用.ToArray()我的LINQ查询,如下所示:
var aggregationResult = (from a in
(from b in collection
where b.SatisfysCondition)
.Aggregate(aggregationFunction)
select a.NeededValue).ToArray();
Run Code Online (Sandbox Code Playgroud)
结果数组的大小总是很小(<100项),因此内存/处理时间不是问题.这是处理我的问题的最佳方法,还是有更好的方法来强制评估LINQ查询?
有没有办法知道StreamReader使用了多少字节的流?
我有一个项目,我们需要读取一个文件,其中包含文本标题,后跟二进制数据的开头.我最初尝试阅读此文件是这样的:
private int _dataOffset;
void ReadHeader(string path)
{
using (FileStream stream = File.OpenRead(path))
{
StreamReader textReader = new StreamReader(stream);
do
{
string line = textReader.ReadLine();
handleHeaderLine(line);
} while(line != "DATA") // Yes, they used "DATA" to mark the end of the header
_dataOffset = stream.Position;
}
}
private byte[] ReadDataFrame(string path, int frameNum)
{
using (FileStream stream = File.OpenRead(path))
{
stream.Seek(_dataOffset + frameNum * cbFrame, SeekOrigin.Begin);
byte[] data = new byte[cbFrame];
stream.Read(data, 0, cbFrame);
return data;
}
return null; …Run Code Online (Sandbox Code Playgroud) 最好是这样做一个连接的查询:
var employer = (from person in db.People
join employer in db.Employers
on person.EmployerID equals employer.EmployerID
where person.PersonID == idPerson
select employer).FirstOrDefault();
Run Code Online (Sandbox Code Playgroud)
或者这样做很容易做到这一点(使用空检查):
var employer = (from person in db.People
where person.PersonID == idPerson
select person).FirstOrDefault().Employer;
Run Code Online (Sandbox Code Playgroud)
显然,在这个中我实际上必须在2个语句中进行以进行空检查.
这里有可读性或性能问题的最佳实践吗?