- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我有以下问题:
IQueryable<T>
来自 LinqToQueryStringIQueryable<T>
用于查询MongoDBIQueryable<T>
用于返回分页数据集以及项目总数以确定页面等IQueryable<T>.Where().Count()
上向计数添加分组依据.这会导致计数操作运行非常缓慢。可能的解决方案:
Expression<Func<T,bool>>
来自原文IQueryable<T>
并将其应用于 mongoCollection<T>.Count(filter)
.这绕过了这个问题。我试图从 IQueryable<T>
中获取“Where” .Expression,然后将 ExpressionType 操作为可在 DynamicExpression.ParseLambda()
中使用的格式.在大多数情况下,在我使用 DateTime 表达式测试代码之前,它工作正常。
我附上了一个 LINQPad 脚本,该脚本使用本地 MongoDB 安装来填充数据,然后使用从 ExpressionVisitor 创建的新表达式进行计数。
我希望有一种更简单的方法可以在新的 MongoDB 中重用原始表达式中的“Where”FilterDefinitionBuilder<T>.Where(originalWhereExpression)
.
代码:
<pre><code><Query Kind="Program">
<Reference><RuntimeDirectory>\System.Linq.dll</Reference>
<Reference><RuntimeDirectory>\System.Linq.Expressions.dll</Reference>
<Reference><RuntimeDirectory>\System.Linq.Queryable.dll</Reference>
<NuGetReference>Faker</NuGetReference>
<NuGetReference>LINQKit.Core</NuGetReference>
<NuGetReference>mongocsharpdriver</NuGetReference>
<NuGetReference>MongoDB.Driver</NuGetReference>
<NuGetReference>NBuilder</NuGetReference>
<NuGetReference>Newtonsoft.Json</NuGetReference>
<NuGetReference>System.Linq.Dynamic</NuGetReference>
<Namespace>FizzWare.NBuilder</Namespace>
<Namespace>LinqKit</Namespace>
<Namespace>MongoDB.Bson</Namespace>
<Namespace>MongoDB.Bson.Serialization.Attributes</Namespace>
<Namespace>MongoDB.Driver</Namespace>
<Namespace>MongoDB.Driver.Builders</Namespace>
<Namespace>MongoDB.Driver.Linq</Namespace>
<Namespace>myAlias = System.Linq.Dynamic</Namespace>
<Namespace>Newtonsoft.Json</Namespace>
<Namespace>System.Linq</Namespace>
<Namespace>System.Linq.Expressions</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
<Namespace>System.Threading.Tasks.Dataflow</Namespace>
</Query>
private string _mongoDBConnectionString = "mongodb://localhost";
private string _mongoDBDatabase = "LinqToQ";
private string _mongoDBCollection = "People";
private IMongoClient _mongoClient;
private IMongoDatabase _mongoDb;
private int _demoCount = 100000;
private bool _doPrep = true;
void Main()
{
_connectToMongoDB();
if (_doPrep)
_prepMongo();
var mongoDataQuery = _queryDemoData().Result;
mongoDataQuery.Expression.ToString().Dump("Original Expression");
var whereFinder = new WhereFinder();
whereFinder.SetWhere(mongoDataQuery.Expression);
var tempColl = _getPeopleCollection();
if (!string.IsNullOrEmpty(whereFinder.WhereClause))
{
var filter = new FilterDefinitionBuilder<Person>();
tempColl.Count(filter.Where(_createWherePredicate<Person>(whereFinder.GetLambdaParts<Person>()))).Dump("Dynamic where count");
}
else
tempColl.Count(FilterDefinition<Person>.Empty).Dump("No filter count");
"Done".Dump();
}
// Define other methods and classes here
//
private void _replaceExpressionTypes(ref StringBuilder whereBuilder, Dictionary<ExpressionType,string> expressionTypes)
{
foreach (var expType in expressionTypes.Keys)
{
whereBuilder.Replace($" {expType} ", $" {expressionTypes[expType]} ");
}
var openBracketCount = whereBuilder.ToString().Count(s => s == char.Parse("("));
var closeBracketCount = whereBuilder.ToString().Count(s=> s==char.Parse(")"));
//whereBuilder.Replace("new DateTime(1974, 1, 1)","\"1974-01-01T00:00:00.00Z\"");
whereBuilder.Insert(0,"(",1);
whereBuilder.Append(")");
$"OpenBrackets: {openBracketCount} vs CloseBrackets: {closeBracketCount}".Dump("Found Brackets");
if(openBracketCount==closeBracketCount)
return;
if (openBracketCount > closeBracketCount)
{
var firstopenBracket = whereBuilder.ToString().IndexOf("(");
whereBuilder.Remove(firstopenBracket,1);
}
var lastCloseBracket = whereBuilder.ToString().LastIndexOf(")");
if(lastCloseBracket>-1)
whereBuilder.Remove(lastCloseBracket,1);
}
private Dictionary<ExpressionType, string> _buildExpressionTypePairs()
{
var result = new Dictionary<ExpressionType, string>();
result.Add(ExpressionType.Not, "!");
result.Add(ExpressionType.Add, "+");
result.Add(ExpressionType.AddChecked, "+");
result.Add(ExpressionType.Subtract, "-");
result.Add(ExpressionType.SubtractChecked, "-");
result.Add(ExpressionType.Multiply, "*");
result.Add(ExpressionType.MultiplyChecked, "*");
result.Add(ExpressionType.Divide, "/");
result.Add(ExpressionType.Modulo, "%");
result.Add(ExpressionType.And, "&");
result.Add(ExpressionType.AndAlso, "&&");
result.Add(ExpressionType.Or, "|");
result.Add(ExpressionType.OrElse, "||");
result.Add(ExpressionType.LessThan, "<");
result.Add(ExpressionType.LessThanOrEqual, "<=");
result.Add(ExpressionType.GreaterThan, ">");
result.Add(ExpressionType.GreaterThanOrEqual, ">=");
result.Add(ExpressionType.Equal, "==");
result.Add(ExpressionType.NotEqual, "!=");
return result;
}
private Expression<Func<Person, bool>> _createWherePredicate<T>(LamdaParts<T> lamdaParts)
{
var whereBuilder = new StringBuilder(lamdaParts.ExpressionString);
_replaceExpressionTypes(ref whereBuilder, _buildExpressionTypePairs());
whereBuilder.ToString().Dump("Manipulated where cluase");
var parameter = Expression.Parameter(lamdaParts.ParamterType, lamdaParts.ExpressionParameter);
//lamdaParts.ParamterType.Dump("Parameter");
//var parameter = Expression.Parameter(typeof(Person), "p");
var expression = myAlias.DynamicExpression.ParseLambda(new[] { parameter }, null, whereBuilder.ToString());
//return Expression.Lambda<Func<Person, bool>>(whereExpression, parameter);
return Expression.Lambda<Func<Person, bool>>(expression.Body, expression.Parameters);
}
private async Task<IMongoQueryable<Person>> _queryDemoData()
{
var people = _getPeopleCollection();
return people.AsQueryable().Where(p => p.DateOfBirth <= new DateTime(1974, 1, 1));
//return people.AsQueryable().Where(p => p.LastName == "Anderson" && p.FirstName.Contains("f") && p.DateOfBirth >= new DateTime(1968, 1, 1) && p.DateOfBirth < new DateTime(1974, 1, 1));
//return people.AsQueryable().Where(p => p.LastName == "Anderson" && p.FirstName.Contains("f") && (p.DateOfBirth>=new DateTime(1968,1,1) && p.DateOfBirth<new DateTime(1974,1,1)));
//return people.AsQueryable().Where(p => p.LastName == "Anderson" && p.FirstName.Contains("f"));
//return people.AsQueryable().Where(p => p.FirstName.Contains("f"));
//return people.AsQueryable().Where(p => p.LastName == "Anderson");
}
private void _prepMongo()
{
_mongoDb.DropCollection(_mongoDBCollection, CancellationToken.None);
var testData = _getDemoList(_demoCount);
var people = _getPeopleCollection();
people.Indexes.CreateOne(Builders<Person>.IndexKeys.Ascending(_ => _.LastName));
people.Indexes.CreateOne(Builders<Person>.IndexKeys.Ascending(_ => _.Email));
testData.ForEachOverTpl((person) =>
{
people.InsertOneAsync(person).Wait();
});
$"Inserted {testData.Count} demo records".Dump();
}
private IList<Person> _getDemoList(int demoCount)
{
var result = Builder<Person>.CreateListOfSize(demoCount)
.All()
.With(p => p.FirstName = Faker.NameFaker.FirstName())
.With(p => p.LastName = Faker.NameFaker.LastName())
.With(p => p.Email = Faker.InternetFaker.Email())
.With(p => p.DateOfBirth = Faker.DateTimeFaker.BirthDay(21,50))
.Build();
return result;
}
private IMongoCollection<Person> _getPeopleCollection()
{
return _mongoDb.GetCollection<Person>(_mongoDBCollection);
}
private void _connectToMongoDB()
{
_mongoClient = new MongoClient(_mongoDBConnectionString);
_mongoDb = _mongoClient.GetDatabase(_mongoDBDatabase);
}
public class Person
{
[BsonId]
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class WhereFinder : MongoDB.Driver.Linq.ExpressionVisitor
{
//private IList<MethodCallExpression> whereExpressions = new List<MethodCallExpression>();
private bool _foundWhere = false;
private bool _setWhere = false;
public string WhereClause { get; set; }
public string Parameter { get; set; }
public LamdaParts<T> GetLambdaParts<T>()
{
return new LamdaParts<T> {
ExpressionParameter=Parameter,
ExpressionString = WhereClause
};
}
public void SetWhere(Expression expression)
{
Visit(expression);
//return whereExpressions;
}
protected override Expression VisitBinary(BinaryExpression node)
{
//$"{node.Left} {_convertNodeType(node.NodeType)} {node.Right}".Dump();
if (_foundWhere && !_setWhere)
{
//node.ToString().Dump("VisitBinary");
$"{node.Left} {_convertNodeType(node.NodeType)} {node.Right}".Dump("Setting Where Clause");
WhereClause= $"{node.Left} {_convertNodeType(node.NodeType)} {node.Right}";
//WhereClause.Dump("WhereClause");
_setWhere=true;
}
return base.VisitBinary(node);
}
private string _convertNodeType(ExpressionType nodeType)
{
switch (nodeType)
{
case ExpressionType.Not:
return "!";
case ExpressionType.Add:
case ExpressionType.AddChecked:
return "+";
case ExpressionType.Subtract:
case ExpressionType.SubtractChecked:
return "-";
case ExpressionType.Multiply:
case ExpressionType.MultiplyChecked:
return "*";
case ExpressionType.Divide:
return "/";
case ExpressionType.Modulo:
return "%";
case ExpressionType.And:
return "&";
case ExpressionType.AndAlso:
return "&&";
case ExpressionType.Or:
return "|";
case ExpressionType.OrElse:
return "||";
case ExpressionType.LessThan:
return "<";
case ExpressionType.LessThanOrEqual:
return "<=";
case ExpressionType.GreaterThan:
return ">";
case ExpressionType.GreaterThanOrEqual:
return ">=";
case ExpressionType.Equal:
return "==";
case ExpressionType.NotEqual:
return "!=";
default:
throw new Exception(string.Format("Unhandled expression type: '{0}'", nodeType));
}
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (_foundWhere)
{
//node.ToString().Dump("VisitParameter");
Parameter=node.ToString();
}
return base.VisitParameter(node);
}
protected override Expression VisitMethodCall(MethodCallExpression expression)
{
if (expression.Method.Name == "Where")
{
//whereExpressions.Add(expression);
_foundWhere = true;
}
if (expression?.Arguments != null)
{
foreach (var arg in expression.Arguments)
{
Visit(arg);
}
}
return expression;
}
}
public class LamdaParts<T>
{
public Type ParamterType
{
get
{
return typeof(T);
}
}
public string ExpressionParameter { get; set; }
public string ExpressionString { get;set;}
}
public static class Extensions
{
public static void ForEachOverTpl<T>(this IEnumerable<T> enumerable, Action<T> call)
{
var cancellationTokenSource = new CancellationTokenSource();
var actionBlock = new ActionBlock<T>(call, new ExecutionDataflowBlockOptions
{
TaskScheduler = TaskScheduler.Current,
MaxDegreeOfParallelism = Environment.ProcessorCount * 2,
CancellationToken = cancellationTokenSource.Token,
});
foreach (T item in enumerable)
{
if (cancellationTokenSource.IsCancellationRequested) return;
actionBlock.Post(item);
}
actionBlock.Complete();
actionBlock.Completion.Wait(cancellationTokenSource.Token);
}
}
</code></pre>
最佳答案
一旦您理解了表达式树和可能的根级表达式方法名称,解决方案就相当简单了。感谢@bolanki 的帮助。
附件是更新的 LINQPad 脚本(测试集 _doPrep = true
):
<Query Kind="Program">
<Reference><RuntimeDirectory>\System.Linq.dll</Reference>
<Reference><RuntimeDirectory>\System.Linq.Expressions.dll</Reference>
<Reference><RuntimeDirectory>\System.Linq.Queryable.dll</Reference>
<NuGetReference>Faker</NuGetReference>
<NuGetReference>mongocsharpdriver</NuGetReference>
<NuGetReference>MongoDB.Driver</NuGetReference>
<NuGetReference>NBuilder</NuGetReference>
<NuGetReference>Newtonsoft.Json</NuGetReference>
<NuGetReference>System.Linq.Dynamic</NuGetReference>
<Namespace>FizzWare.NBuilder</Namespace>
<Namespace>MongoDB.Bson</Namespace>
<Namespace>MongoDB.Bson.Serialization.Attributes</Namespace>
<Namespace>MongoDB.Driver</Namespace>
<Namespace>MongoDB.Driver.Builders</Namespace>
<Namespace>MongoDB.Driver.Linq</Namespace>
<Namespace>myAlias = System.Linq.Dynamic</Namespace>
<Namespace>Newtonsoft.Json</Namespace>
<Namespace>System.Linq</Namespace>
<Namespace>System.Linq.Expressions</Namespace>
<Namespace>System.Threading.Tasks</Namespace>
<Namespace>System.Threading.Tasks.Dataflow</Namespace>
</Query>
private string _mongoDBConnectionString = "mongodb://localhost";
private string _mongoDBDatabase = "LinqToQ";
private string _mongoDBCollection = "People";
private IMongoClient _mongoClient;
private IMongoDatabase _mongoDb;
private int _demoCount = 2000000;
private bool _doPrep = false;
void Main()
{
_connectToMongoDB();
// Should demo data be generated
if (_doPrep)
_prepMongo();
// Get the queryable to test with
var mongoDataQuery = _getIQueryable();
// Print the original expression
//mongoDataQuery.Expression.ToString().Dump("Original Expression");
// Evaluate the expression and try find the where expression
var whereFinder = new WhereFinder<Person>(mongoDataQuery.Expression);
// Get the MongoCollection to be Filtered and Count
var tempColl = _getPeopleCollection();
if (whereFinder.FoundWhere)
{
//whereFinder.TheWhereExpression.ToString().Dump("Calculated where expression");
var filter = new FilterDefinitionBuilder<Person>();
var stopwatch = new Stopwatch();
stopwatch.Start();
tempColl.Count(filter.Where(whereFinder.TheWhereExpression)).Dump("Dynamic where count");
var afterCalculatedWhere = stopwatch.Elapsed;
mongoDataQuery.Count().Dump("IQueryable<T> where count");
var afterIQuerableWhere = stopwatch.Elapsed;
stopwatch.Stop();
$"Calculated where:{afterCalculatedWhere:c}\nIQueryable where:{afterIQuerableWhere:c}".Dump("Where Durations");
}
else
tempColl.Count(FilterDefinition<Person>.Empty).Dump("No filter count");
"Done".Dump();
}
///////////////////////////////////////////////////////
// END SOLUTION
///////////////////////////////////////////////////////
private IMongoQueryable<Person> _getIQueryable()
{
var people = _getPeopleCollection();
//return people.AsQueryable().Where(p => p.DateOfBirth <= new DateTime(1974, 1, 1));
return people.AsQueryable().Where(p => p.LastName == "Anderson" && p.FirstName.Contains("f") && p.DateOfBirth >= new DateTime(1968, 1, 1) && p.DateOfBirth < new DateTime(1974, 1, 1));
//return people.AsQueryable().Where(p => p.LastName == "Anderson" && p.FirstName.Contains("f") && (p.DateOfBirth>=new DateTime(1968,1,1) && p.DateOfBirth<new DateTime(1974,1,1)));
//return people.AsQueryable().Where(p => p.LastName == "Anderson" && p.FirstName.Contains("f"));
//return people.AsQueryable().Where(p => p.FirstName.Contains("f"));
//return people.AsQueryable().Where(p => p.LastName == "Anderson");
}
public class Person
{
[BsonId]
public string Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public DateTime DateOfBirth { get; set; }
}
public class WhereFinder<T> : MongoDB.Driver.Linq.ExpressionVisitor
{
private bool _processingWhere = false;
private bool _processingLambda = false;
public ParameterExpression _parameterExpression { get; set; }
public WhereFinder(Expression expression)
{
Visit(expression);
}
public Expression<Func<T, bool>> TheWhereExpression { get; set; }
public bool FoundWhere
{
get { return TheWhereExpression != null; }
}
protected override Expression VisitBinary(BinaryExpression node)
{
var result = base.VisitBinary(node);
if(_processingWhere)
TheWhereExpression = (Expression<Func<T, bool>>)Expression.Lambda(node, _parameterExpression);
return result;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (_processingWhere || _processingLambda || _parameterExpression==null)
_parameterExpression = node;
return base.VisitParameter(node);
}
protected override Expression VisitMethodCall(MethodCallExpression expression)
{
string methodName = expression.Method.Name;
if (TheWhereExpression==null && ( methodName == "Where" || methodName == "Contains"))
{
_processingWhere = true;
if (expression?.Arguments != null)
foreach (var arg in expression.Arguments)
Visit(arg);
_processingWhere = false;
}
return expression;
}
protected override Expression VisitLambda(LambdaExpression exp)
{
if (_parameterExpression == null)
_parameterExpression = exp.Parameters?.FirstOrDefault();
TheWhereExpression = (Expression<Func<T, bool>>)Expression.Lambda(exp.Body, _parameterExpression);
return exp;
}
}
///////////////////////////////////////////////////////
// END SOLUTION
///////////////////////////////////////////////////////
///////////////////////////////////////////////////////
// BEGIN DEMO DATA
///////////////////////////////////////////////////////
private void _prepMongo()
{
_mongoDb.DropCollection(_mongoDBCollection, CancellationToken.None);
var testData = _getDemoList(_demoCount);
var people = _getPeopleCollection();
people.Indexes.CreateOne(Builders<Person>.IndexKeys.Ascending(_ => _.FirstName));
people.Indexes.CreateOne(Builders<Person>.IndexKeys.Ascending(_ => _.LastName));
people.Indexes.CreateOne(Builders<Person>.IndexKeys.Ascending(_ => _.Email));
people.Indexes.CreateOne(Builders<Person>.IndexKeys.Ascending(_ => _.DateOfBirth));
$"Inserting ...{testData.Count}... demo records".Dump();
Extensions.ForEachOverTpl<Person>(testData, (person) =>
{
people.InsertOneAsync(person).Wait();
});
$"Inserted {testData.Count} demo records".Dump();
}
private IList<Person> _getDemoList(int demoCount)
{
var result = Builder<Person>.CreateListOfSize(demoCount)
.All()
.With(p => p.FirstName = Faker.NameFaker.FirstName())
.With(p => p.LastName = Faker.NameFaker.LastName())
.With(p => p.Email = Faker.InternetFaker.Email())
.With(p => p.DateOfBirth = Faker.DateTimeFaker.BirthDay(21, 50))
.Build();
return result;
}
private IMongoCollection<Person> _getPeopleCollection()
{
return _mongoDb.GetCollection<Person>(_mongoDBCollection);
}
private void _connectToMongoDB()
{
_mongoClient = new MongoClient(_mongoDBConnectionString);
_mongoDb = _mongoClient.GetDatabase(_mongoDBDatabase);
}
///////////////////////////////////////////////////////
// END DEMO DATA
///////////////////////////////////////////////////////
public static class Extensions
{
public static void ForEachOverTpl<T>(this IEnumerable<T> enumerable, Action<T> call)
{
var cancellationTokenSource = new CancellationTokenSource();
var actionBlock = new ActionBlock<T>(call, new ExecutionDataflowBlockOptions
{
TaskScheduler = TaskScheduler.Current,
MaxDegreeOfParallelism = Environment.ProcessorCount * 2,
CancellationToken = cancellationTokenSource.Token,
});
foreach (T item in enumerable)
{
if (cancellationTokenSource.IsCancellationRequested) return;
actionBlock.Post(item);
}
actionBlock.Complete();
actionBlock.Completion.Wait(cancellationTokenSource.Token);
}
}
更新:-- 修复了包含 Take、OrderBy 等的表达式
public class WhereFinder<T> : MongoDB.Driver.Linq.ExpressionVisitor
{
private bool _processingWhere = false;
private bool _processingLambda = false;
public ParameterExpression _parameterExpression { get; set; }
public WhereFinder(Expression expression)
{
Visit(expression);
}
public Expression<Func<T, bool>> TheWhereExpression { get; set; }
public bool FoundWhere
{
get { return TheWhereExpression != null; }
}
protected override Expression Visit(Expression exp)
{
return base.Visit(exp);
}
protected override Expression VisitBinary(BinaryExpression node)
{
var result = base.VisitBinary(node);
if (_processingWhere)
{
TheWhereExpression = (Expression<Func<T, bool>>) Expression.Lambda(node, _parameterExpression);
}
return result;
}
protected override Expression VisitParameter(ParameterExpression node)
{
if (_processingWhere || _processingLambda || _parameterExpression == null)
_parameterExpression = node;
return base.VisitParameter(node);
}
protected override Expression VisitMethodCall(MethodCallExpression expression)
{
string methodName = expression.Method.Name;
if (methodName == "Where")
_processingWhere = true;
if (expression?.Arguments != null)
foreach (var arg in expression.Arguments)
Visit(arg);
_processingWhere = false;
return expression;
}
protected override Expression VisitLambda(LambdaExpression exp)
{
if (_processingWhere)
{
if (_parameterExpression == null)
_parameterExpression = exp.Parameters?.FirstOrDefault();
TheWhereExpression = (Expression<Func<T, bool>>)Expression.Lambda(exp.Body, _parameterExpression);
}
return exp;
}
}
关于c# - 是否可以获取 IQueryable<T> 上使用的谓词 (Expression<Func<T,bool>>) 并将其应用于另一个 Lambda 函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42223936/
我对这个错误很困惑: Cannot implicitly convert type 'System.Func [c:\Program Files (x86)\Reference Assemblies\
考虑这段代码: pub trait Hello { fn hello(&self); } impl Hello for Any { fn hello(&self) {
问题很简单。是否可以构造这样一个类型 T,对于它下面的两个变量声明会产生不同的结果? T t1 = {}; T t2{}; 我已经研究 cppreference 和标准一个多小时了,我了解以下内容:
Intellij idea 给我这个错误:“Compare (T, T) in Comparator cannot be applied to (T, T)” 对于以下代码: public class
任何人都可以告诉我 : n\t\t\t\t\n\t\t\t 在以下来自和 dwr 服务的响应中的含义和用途是什么. \r\n\t\t\t \r\n\t\t\t
让 T 成为一个 C++ 类。 下面三个指令在行为上有什么区别吗? T a; T a(); T a = T(); T 为不带参数的构造函数提供了显式定义这一事实是否对问题有任何改变? 后续问题:如果
Rust中的智能指针是什么 智能指针(smart pointers)是一类数据结构,是拥有数据所有权和额外功能的指针。是指针的进一步发展 指针(pointer)是一个包含内存地
比如我有一个 vector vector > v={{true,1},{true,2},{false,3},{false,4},{false,5},{true,6},{false,7},{true,8
我有一个来自 .xls 电子表格的数据框,我打印了 print(df.columns.values) 列,输出包含一个名为:Poll Responses\n\t\t\t\t\t。 我查看了 Excel
This question already has answers here: What are good reasons for choosing invariance in an API like
指针类型作为类型前缀与在类型前加斜杠作为后缀有什么区别。斜线到底是什么意思? 最佳答案 语法 T/~ 和 T/& 基本上已被弃用(我什至不确定编译器是否仍然接受它)。在向新向量方案过渡的初始阶段,[T
我正在尝试找到一种方法来获取模板参数的基类。 考虑以下类: template class Foo { public: Foo(){}; ~Foo(){};
这是一个让我感到困惑的小问题。我不知道如何描述它,所以只看下面的代码: struct B { B() {} B(B&) { std::cout ::value #include
为什么有 T::T(T&) 而 T::T(const T&) 更适合 copy ? (大概是用来实现move语义的???) 原始描述(被melpomene证明是错误的): 在C++11中,支持了一种新
在 Java 7 中使用 eclipse 4.2 并尝试实现 List 接口(interface)的以下方法时,我收到了警告。 public T[] toArray(T[] a) { ret
假设有三个函数: def foo[T](a:T, b:T): T = a def test1 = foo(1, "2") def test2 = foo(List(), ListBuffer()) 虽
我对柯里化(Currying)和非柯里化(Currying)泛型函数之间类型检查的差异有点困惑: scala> def x[T](a: T, b: T) = (a == b) x: [T](a: T,
考虑一个类A,我如何编写一个具有与相同行为的模板 A& pretty(A& x) { /* make x pretty */ return x; } A pretty(A&& x) {
Eclipse 表示由于泛型类型橡皮擦,类型参数不允许使用 instanceof 操作。 我同意在运行时不会保留任何类型信息。但是请考虑以下类的通用声明: class SomeClass{ T
在 C++14 中: 对于任何整数或枚举类型 T 以及对于任何表达式 expr: 有没有区别: struct S { T t { expr }; }; 和 struct S { T t = { exp
我是一名优秀的程序员,十分优秀!