我刚刚在我的机器上安装了.NET Framework 4.6,然后使用Visual Studio 2013创建了一个针对.NET Framework 4.6的ConsoleApplication.
我在Main方法中写了以下内容:
string test = "Hello";
string format = $"{test} world!";
Run Code Online (Sandbox Code Playgroud)
但这不编译.在Visual Studio 2015中执行相同操作.
为什么?
我刚看了.NET Framework 的Skip/ Takeextension方法的源代码(在IEnumerable<T>类型上),发现内部实现正在使用该GetEnumerator方法:
// .NET framework
public static IEnumerable<TSource> Skip<TSource>(this IEnumerable<TSource> source, int count)
{
if (source == null) throw Error.ArgumentNull("source");
return SkipIterator<TSource>(source, count);
}
static IEnumerable<TSource> SkipIterator<TSource>(IEnumerable<TSource> source, int count)
{
using (IEnumerator<TSource> e = source.GetEnumerator())
{
while (count > 0 && e.MoveNext()) count--;
if (count <= 0)
{
while (e.MoveNext()) yield return e.Current;
}
}
}
Run Code Online (Sandbox Code Playgroud)
假设我有IEnumerable<T>1000个元素(底层类型是List<T>).如果我正在做list.Skip(990)会怎么样.拿(10)?在进入最后十个元素之前,它是否会通过990首元素进行迭代?(这就是我的理解).如果是,那么我不明白为什么微软没有实现这样的Skip方法:
// Not tested... just to show the …Run Code Online (Sandbox Code Playgroud) 我有两个非常简单的对象:
public class CategoryDto
{
public string Id { get; set; }
public string MyValueProperty { get; set; }
}
public class Category
{
public string Id { get; set; }
[MapTo("MyValueProperty")]
public string Key { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
使用AutoMapper Category将a 映射到a CategoryDto时,我想要以下行为:
除了具有该MapTo属性的属性之外,应该像往常一样映射属性.在这种情况下,我必须读取Attribute的值来查找target属性.source属性的值用于在destination属性中查找要注入的值(借助字典).一个例子总是好于1000字......
例:
Dictionary<string, string> keys =
new Dictionary<string, string> { { "MyKey", "MyValue" } };
Category category = new Category();
category.Id = "3";
category.Key = "MyKey";
CategoryDto result = Map<Category, CategoryDto>(category);
result.Id …Run Code Online (Sandbox Code Playgroud) 我才发现,原来,因为.NET 4.6,有一个新的方法FromException上Task的对象,我想知道什么是在抛出异常的最佳方式async方法
这里有两个例子:
internal class Program
{
public static void Main(string[] args)
{
MainAsync().Wait();
}
private static async Task MainAsync()
{
try
{
Program p = new Program();
string x = await p.GetTest1(@"C:\temp1");
}
catch (Exception e)
{
// Do something here
}
}
// Using the new FromException method
private Task<string> GetTest1(string filePath)
{
if (!Directory.Exists(filePath))
{
return Task.FromException<string>(new DirectoryNotFoundException("Invalid directory name."));
}
return Task.FromResult(filePath);
}
// Using the normal throw keyword
private …Run Code Online (Sandbox Code Playgroud) 我正在寻找一种方法来存储Expression<Func<T, TProperty>>用于订单元素的集合,然后针对IQueryable<T>对象执行存储列表(底层提供者是实体框架).
例如,我想做这样的事情(这是伪代码):
public class Program
{
public static void Main(string[] args)
{
OrderClause<User> orderBys = new OrderClause<User>();
orderBys.AddOrderBy(u => u.Firstname);
orderBys.AddOrderBy(u => u.Lastname);
orderBys.AddOrderBy(u => u.Age);
Repository<User> userRepository = new Repository<User>();
IEnumerable<User> result = userRepository.Query(orderBys.OrderByClauses);
}
}
Run Code Online (Sandbox Code Playgroud)
order by子句(要订购的属性):
public class OrderClause<T>
{
public void AddOrderBy<TProperty>(Expression<Func<T, TProperty>> orderBySelector)
{
_list.Add(orderBySelector);
}
public IEnumerable<Expression<Func<T, ???>>> OrderByClauses
{
get { return _list; }
}
}
Run Code Online (Sandbox Code Playgroud)
使用我的查询方法的存储库:
public class Repository<T>
{
public IEnumerable<T> Query(IEnumerable<OrderClause<T>> clauses)
{ …Run Code Online (Sandbox Code Playgroud) 我尝试将一行使用String.Format两次的代码迁移到新的.NET Framework 6字符串插值功能,但直到现在我还没有成功.
var result = String.Format(String.Format("{{0:{0}}}{1}",
strFormat, withUnit ? " Kb" : String.Empty),
(double)fileSize / FileSizeConstant.KO);
Run Code Online (Sandbox Code Playgroud)
一个工作的例子可能是:
var result = String.Format(String.Format("{{0:{0}}}{1}",
"N2", " Kb"), 1000000000 / 1048576D);
Run Code Online (Sandbox Code Playgroud)
产量:953,67 Kb
这是可能的还是我们需要在这种特殊情况下使用旧结构?
我正在尝试使用docker配置IdentityServer4,但我无法使其工作.首先,我获取了身份服务器文档的Client Credential示例:使用Client Credentials保护API
IdentityServer
托管在端口5000上
WebApi
托管在端口5001上
在我的WebApi文件的Configure方法中,Startup.cs我做了以下(问题可能在这里):
app.UseIdentityServerAuthentication(new IdentityServerAuthenticationOptions
{
Authority = "http://web:5000",
RequireHttpsMetadata = false,
ApiName = "api1"
});
Run Code Online (Sandbox Code Playgroud)
客户
和客户
// Everything is fine here...
var disco = await DiscoveryClient.GetAsync("http://localhost:5000");
var tokenClient = new TokenClient(disco.TokenEndpoint, "client", "secret");
var tokenResponse = await tokenClient.RequestClientCredentialsAsync("api");
// This does not work
var client = new HttpClient();
client.SetBearerToken(tokenResponse.AccessToken);
var response = await client.GetAsync("http://localhost:5001/identity");
Run Code Online (Sandbox Code Playgroud)
问题可能出在我的WebApi中:
1)如果我将权限设置为localhost:5000,我收到一个内部服务器错误:"无法从以下地址获取配置:' http:// localhost:5000/.well-known/openid-configuration '"这是有道理的,因为localhost :5000在此容器中未知
2)如果我将权限设置为http:// web:5000,我会收到授权错误:"颁发者验证失败.发行者:' http:// localhost:5000 '.不匹配:validationParameters.ValidIssuer:' http://web:5000 …
我创建了一个VSIX Project(使用Visual Studio Extensibility)引用a C# Project Template; 它看起来像这样:
<TemplateData>
<Name>...</Name>
<Description>...</Description>
<Icon>...</Icon>
<ProjectType>Web</ProjectType>
<ProjectSubType>CSharp</ProjectSubType>
<TemplateGroupID>Web</TemplateGroupID>
<DefaultName>WebApplication</DefaultName>
</TemplateData>
<TemplateContent>
<ProjectCollection>
<ProjectTemplateLink ProjectName="My Web Application">
Projects\WebApplication\ProjectTemplate.vstemplate
</ProjectTemplateLink>
<ProjectTemplateLink ProjectName="My Windows Library">
Projects\Library\ProjectTemplate.vstemplate
</ProjectTemplateLink>
</ProjectCollection>
</TemplateContent>
Run Code Online (Sandbox Code Playgroud)
一切都按预期工作,但我Project Template总是出现在Visual C#Visual Studio New Project窗体的默认根类别中.
我想把它放在里面Web category.

注意:
<ProjectType>CSharp</ProjectType>
<ProjectSubType>Web</ProjectSubType>
Run Code Online (Sandbox Code Playgroud)
=>模板出现在默认的根类别中
<ProjectType>Web</ProjectType>
<ProjectSubType>CSharp</ProjectSubType>
Run Code Online (Sandbox Code Playgroud)
=>模板不可见!
我在使用属性索引器(C#)时发现了一种奇怪的行为.
考虑以下程序:
public class Program
{
public static void Main(string[] args)
{
CustomMessageList cml = new CustomMessageList
{
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage(), // Type1
new CustomMessage() // Type1
};
// Empty
IEnumerable<CustomMessage> x1 = cml[MessageType.Type2];
// Contains all elements (6)
IEnumerable<CustomMessage> x2 = cml[0]; // MessageType.Type1 ????
// Does not compile!
IEnumerable<CustomMessage> x3 = cml[1]; // NOT MessageType.Type2 ????
}
}
public class CustomMessageList : List<CustomMessage> …Run Code Online (Sandbox Code Playgroud) 您将如何测试与时间相关的方法?
一个简单的例子可能是:
public static int GetAge(DateTime birthdate)
{
// ...
}
[TestMethod]
public void GetAgeTest()
{
// This is only ok for year 2013 !
Assert.AreEqual(GetAge(new DateTime(2000, 1, 1)), 13);
}
Run Code Online (Sandbox Code Playgroud)
问题是它仅适用于当前年份(在本例中为 2013)。新的一年一开始,我就必须重写所有与时间相关的测试......
单元测试这种方法的最佳方法是什么?
c# ×9
.net ×8
.net-core ×1
async-await ×1
automapper ×1
c#-6.0 ×1
docker ×1
enums ×1
exception ×1
ienumerable ×1
indexer ×1
lambda ×1
linq ×1
mapping ×1
performance ×1
properties ×1
skip-take ×1
task ×1
templates ×1
unit-testing ×1
vsix ×1