小编mbu*_*ill的帖子

如何使用LINQ查找特定属性的副本?

Customer customerOne = new Customer("John", "Doe");
Customer customerTwo = new Customer("Super", "Man");
Customer customerThree = new Customer("Crazy", "Guy");
Customer customerFour = new Customer("Jane", "Doe");
Customer customerFive = new Customer("Bat", "Man");

List<Customer> customers = new List<Customer>();
customers.Add(customerOne);
customers.Add(customerTwo);
customers.Add(customerThree);
customers.Add(customerFour);
customers.Add(customerFive);
Run Code Online (Sandbox Code Playgroud)

LINQ查询将为具有相同姓氏的所有客户返回可枚举的内容?

结果应该包括一个例子:John Doe,Jane Doe,Super Man和Bat Man

c# linq

25
推荐指数
3
解决办法
1万
查看次数

在Lazy <T>中转换接口类型

我想要这样的东西:

public interface IAnimal
{ }

public class Dog : IAnimal
{
    public Dog() {}
}

public class Cat : IAnimal
{
    public Cat() {}
}

public abstract class TestClassBase
{
    public TestClassBase()
    {
        _lazyAnimal = CreateLazyAnimal();
    }

    private Lazy<IAnimal> _lazyAnimal = null;
    public IAnimal Animal
    {
        get
        { 
            IAnimal animal = null;
            if (_lazyAnimal != null)
                animal = _lazyAnimal.Value;

            return animal;
        }
    }

    // Could be overridden to support other animals
    public virtual Lazy<IAnimal> CreateLazyAnimal()
    {
        // default animal …
Run Code Online (Sandbox Code Playgroud)

c# generics

14
推荐指数
2
解决办法
4473
查看次数

如何从Action <T>获取方法的自定义属性?

如何从Action<T>委托中获取方法的自定义属性?

例:

//simple custom attribute
public class StatusAttribute : Attribute
{

    public string Message { get; set; } = string.Empty;
}

// an extension methodto wrap MethodInfo.GetCustomAttributes(Type, Bool) with
// generics for the custom Attribute type
public static class MethodInfoExtentions
{
    public static IEnumerable<TAttribute> GetCustomAttributes<TAttribute>(this MethodInfo methodInfo, bool inherit) where TAttribute : Attribute
    {
        object[] attributeObjects = methodInfo.GetCustomAttributes(typeof(TAttribute), inherit);
        return attributeObjects.Cast<TAttribute>();
    }
}

// test class with a test method to implment the custom attribute
public class Foo …
Run Code Online (Sandbox Code Playgroud)

c# reflection

7
推荐指数
1
解决办法
5172
查看次数

父控件ScrollViewer滚动而不是子控件ScrollViewer

我有这个:

<Window x:Class="ScrollTest.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow"
        Height="450"
        Width="525">
    <ScrollViewer ScrollViewer.HorizontalScrollBarVisibility="Visible"
                  ScrollViewer.VerticalScrollBarVisibility="Visible">
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="Auto" />
                <RowDefinition Height="*" />
            </Grid.RowDefinitions>

            <GroupBox Grid.Row="0"
                      Header="Stuff"
                      Height="200">
                <TextBlock Text="Lots of controls go here"
                           HorizontalAlignment="Center"
                           VerticalAlignment="Center" />
            </GroupBox>
            <TabControl Grid.Row="1">
                <TabItem Header="Main Tab">
                    <TextBox MinHeight="100"
                             HorizontalAlignment="Stretch"
                             VerticalAlignment="Stretch"
                             HorizontalContentAlignment="Left"
                             VerticalContentAlignment="Top"
                             ScrollViewer.HorizontalScrollBarVisibility="Visible"
                             ScrollViewer.VerticalScrollBarVisibility="Visible"
                             AcceptsReturn="True" />
                </TabItem>
            </TabControl>
        </Grid>
    </ScrollViewer>
</Window>
Run Code Online (Sandbox Code Playgroud)

当我添加太多的行成TextBox,而不是ScrollViewerTextBox使用,箱体延伸和最外层ScrollViewer使用.我可以在不修复TextBox或高度的情况下防止这种情况TabControl吗?

更新:

如果我删除MinHeightTextBox,并设置MaxLines为5,这是我得到:

MinHeight已删除,MaxLines设置为5

如果我添加了第6行,则使用TextBoxs 的滚动条ScrollViewer …

c# wpf scroll parent-child scrollviewer

6
推荐指数
1
解决办法
2241
查看次数

WCF - HTTP上的二进制编码抛出客户端和服务绑定不匹配异常

例外:

服务http:// localhost:1500/MyService.svc不支持内容类型application/soap + msbin1 .客户端和服务绑定可能不匹配.

客户端配置:

  <system.serviceModel>
    <bindings>

    <customBinding>
        <binding name="NetHttpBinding" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">
          <binaryMessageEncoding />
          <httpTransport allowCookies="false" bypassProxyOnLocal="false"
                         hostNameComparisonMode="StrongWildcard" maxBufferSize="65536"
                         maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                         transferMode="Buffered" useDefaultWebProxy="true" />
        </binding>
      </customBinding>

    </bindings>
    <client>
      <endpoint address="http://localhost:1500/MyService.svc"
        binding="customBinding" bindingConfiguration="NetHttpBinding"
        contract="APP.BLL.IMyServiceContract" name="MyServiceEndpoint" />
    </client>
  </system.serviceModel>
Run Code Online (Sandbox Code Playgroud)

服务器配置:

  <system.serviceModel>
    <bindings>
      <customBinding>
        <binding name="NetHttpBinding" closeTimeout="00:01:00"
          openTimeout="00:01:00" receiveTimeout="00:10:00" sendTimeout="00:01:00">
          <binaryMessageEncoding />
          <httpTransport allowCookies="false" bypassProxyOnLocal="false"
                         hostNameComparisonMode="StrongWildcard" maxBufferSize="65536"
                         maxBufferPoolSize="524288" maxReceivedMessageSize="65536"
                         transferMode="Buffered" useDefaultWebProxy="true" />
        </binding>
      </customBinding>
    </bindings>

    <services>
      <service name="MyAppService">
        <endpoint address="" binding="customBinding" bindingConfiguration="NetHttpBinding"
                  contract="APP.BLL.IMyServiceContract">
        </endpoint>
      </service>
    </services>

    <behaviors> …
Run Code Online (Sandbox Code Playgroud)

c# wcf

5
推荐指数
0
解决办法
8508
查看次数

JSON.NET 忽略集合类型对象上的 ISerializable

我有一个包装好的列表,如下所示:

[JsonObject(MemberSerialization.Fields)]
public class OrderManager : IEnumerable<Order>, ISerializable
{
    public OrderManager()
    { }

    private List<Order> orders = new List<Order>();

    public void AddOrder(OrderInfo orderInfo)
    {
        // do the work of making an order object from an OrderInfo.
        // Add the new order object to the private list of orders
        // orders.Add(order);
    }

    public IEnumerator<Order> GetEnumerator()
    {
        return orders.GetEnumerator();
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return orders.GetEnumerator();
    }

    public OrderManager(SerializationInfo info, StreamingContext context)
    {
        // do custom serialization work here (never gets hit)
    } …
Run Code Online (Sandbox Code Playgroud)

c# json.net

5
推荐指数
1
解决办法
2845
查看次数

在GetAsync上使用await时,HttpClient不会抛出异常

我正在使用以下代码获取端点并将其写入缓存:

public async Task UpdateCacheFromHttp(string Uri)
{
    if (string.IsNullOrEmpty(Uri))
        return;

    var httpClient = new HttpClient();
    var response = await httpClient.GetAsync(Uri);

    if ((response != null) && (response.IsSuccessStatusCode))
    {
        var responseStream = await response.Content.ReadAsStreamAsync();
        WriteToCache(responseStream);
    }
}
Run Code Online (Sandbox Code Playgroud)

代码在IIS上运行.

如果无法访问端点,我希望GetAsync抛出异常.即使使用Try-Catch,它也似乎永远不会失败.GetAsync永远不会返回(我在HttpClient上尝试了5秒的超时,仍然没有返回).

这会引发异常:

public Task UpdateCacheFromHttp(string Uri)
{
    var updateCacheTask = Task.Factory.StartNew(new Action(() =>
    {
        if (string.IsNullOrEmpty(Uri))
            return;

        var httpClient = new HttpClient();
        var response = httpClient.GetAsync(Uri).Result;

        if (response.IsSuccessStatusCode)
        {
            var responseStream = response.Content.ReadAsStreamAsync().Result;
            WriteToCache(responseStream);
        }
    }));

    return updateCacheTask;
}
Run Code Online (Sandbox Code Playgroud)

我得到了预期的"无法连接到远程服务器".

我怀疑它与IIS中运行的代码有关,但为什么呢?如何在不需要启动新任务的情况下正确抛出异常?

c# task-parallel-library async-await

5
推荐指数
1
解决办法
5632
查看次数

队列调用异步方法

我有一个名为Refresh的异步操作.如果在第一次完成之前进行第二次刷新调用,我需要对其进行排队.这就是我所拥有的:

public async Task Refresh(RefreshArgs refreshArgs)
{
    await EnqueueRefreshTask(refreshArgs);
}

private Queue<RefreshArgs> refreshQueue =
    new Queue<RefreshArgs>();

private async Task EnqueueRefreshTask(RefreshArgs refreshArgs)
{
    refreshQueue.Enqueue(refreshArgs);

    await ProcessRefreshQueue();
}

private Task currentRefreshTask = null;

private async Task ProcessRefreshQueue()
{
    if ((currentRefreshTask == null) || (currentRefreshTask.IsCompleted))
    {
        if (refreshQueue.Count > 0)
        {
            var refreshArgs = refreshQueue.Dequeue();

            currentRefreshTask = DoRefresh(refreshArgs);
            await currentRefreshTask;

            await ProcessRefreshQueue();
        }           
    }
}

private async Task DoRefresh(RefreshArgs refreshArgs)
{
    // Lots of code here, including calls to a server that are …
Run Code Online (Sandbox Code Playgroud)

c# queue async-await

5
推荐指数
1
解决办法
2203
查看次数

无法从标记为async的方法返回IObservable <T>

这个人为的例子大致是我的代码的结构:

public abstract class SuperHeroBase
{
    protected SuperHeroBase() { }

    public async Task<CrimeFightingResult> FightCrimeAsync()
    {
        var result = new CrimeFightingResult();

        result.State = CrimeFightingStates.Fighting;

        try
        {
            await FightCrimeOverride(results);
        } 
        catch
        {
            SetError(results);
        }

        if (result.State == CrimeFightingStates.Fighting)
            result.State = CrimeFightingStates.GoodGuyWon;

        return result;
    }

    protected SetError(CrimeFightingResult results)
    {
        result.State = CrimeFightingStates.BadGuyWon;
    }

    protected abstract Task FightCrimeOverride(CrimeFightingResult results);
}

public enum CrimeFightingStates
{
    NotStarted,
    Fighting,
    GoodGuyWon, // success state
    BadGuyWon // error state
}

public class CrimeFightingResult
{
    internal class CrimeFightingResult() { } …
Run Code Online (Sandbox Code Playgroud)

c# system.reactive async-await

5
推荐指数
1
解决办法
140
查看次数

使用 AngularUI Router 动态加载控制器

ui-router在一个有几十个模板的应用程序中使用。每个模板都有一个控制器。

从我一直在阅读的内容来看,这样的事情(设置路线)应该可以工作:

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
    .state('start', {
      url: '/start',
      templateUrl: 'partials/start.html',
      controller: 'StartCtrl'
    })
});
Run Code Online (Sandbox Code Playgroud)

那是假设之前定义了 StartCtrl。该应用程序最终将拥有数十个控制器,并且不希望一次性下载所有控制器的开销。如何仅在请求模板时加载控制器?

angularjs angular-ui-router

3
推荐指数
1
解决办法
6863
查看次数

过载发生器

是否有应用程序或网站,我可以输入参数信息(类型和变量名称),它们的默认值,并让它生成方法重载的所有组合?

我有一个类,构造函数可以接受五个不同类型的参数.参数被映射到属性,其中没有一个具有公共setter.每个参数都有一个默认值.

我希望我的类为所有参数的各种组合(从无参数到五个参数的任何和所有组合)重载构造函数.为了使其更加混乱,其中一个参数可以作为特定类型或字符串传递,并且我希望各种重载组合将其考虑在内.

更新:

我同意这种设计可能不是最好的.有问题的类是我使用的类似于WPF的DependencyProperty的PropertyMetadata类的类.为属性支持分配值,并在此时传入元数据类的新实例.它迫使我的手创建这个级联的构造函数重载系列.例:

private ModelProperty<UserModel, string> firstNameProperty =
  RegisterProperty(p => p.FirstName, new ModelPropertyMetadata(**** lots of overloads here ****));
public string FirstName
{
     get { return GetValue(firstNameProperty); }
     set { SetValue(firstNameProperty, value); }
}
Run Code Online (Sandbox Code Playgroud)

也许这不是最好的设计.我可以将ModelPropertyMetadata扩展到描述特定重载的新类,但这似乎就像是将问题推到了其他地方.关于如何改进这种设计的任何想法?

c#

0
推荐指数
1
解决办法
151
查看次数