int x;
string str = Console.ReadLine();
// Вариант с Parse
try
{
x = int.Parse(str);
}
catch (Exception)
{
x = 0;
Console.WriteLine("Неверные данные");
}
// Вариант с Convert
try
{
x = Convert.ToInt32(str);
}
catch (Exception)
{
x = 0;
Console.WriteLine("Неверные данные");
}
// Вариант с TryParse
if (!int.TryParse(str, out x))
{
Console.WriteLine("Неверные данные");
}
// Вариант с TryParse, если ноль устраивает
int.TryParse(str, out x);
private new Rigidbody2D rigidbody2D;
void Start()
{
rigidbody2D = GetComponent<Rigidbody2D>();
}
void IgnoreException(Action funcName)
{
try{ funcName(); }
catch(Exception){}
}
void Func()
{
// код
}
void MyMethod()
{
IgnoreException(() =>
{
Func();
});
// Если запустить просто метод без параметров и возвращаемого значения, то можно так:
IgnoreException(Func);
}
private ViewModel SelectModel(Model model) {}
). public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
if ((bool)value)
{
return parameter != null ? Visibility.Collapsed : Visibility.Hidden;
}
return Visibility.Visible;
}
xmlns:converters="clr-namespace:MyProject.Converters"
<CheckBox x:Name="Checkbox1" Content="Чекбокс 1"/>
<CheckBox x:Name="Checkbox2" Content="Чекбокс 2"/>
<ToggleButton Content="Кнопка">
<ToggleButton.IsEnabled>
<MultiBinding Converter="{converters:BooleanMultiConverter Type=AllTrue}">
<Binding Path="IsChecked" ElementName="Checkbox1"/>
<Binding Path="IsChecked" ElementName="Checkbox2"/>
</MultiBinding>
</ToggleButton.IsEnabled>
</ToggleButton>
using System;
using System.Linq;
using System.Windows;
using System.Windows.Data;
using System.Windows.Markup;
namespace MyProject.Converters
{
public class BooleanMultiConverter : MarkupExtension, IMultiValueConverter
{
/// <summary>
/// Перечисление типа конвертера
/// </summary>
public enum Types
{
AllTrue,
AllFalse,
AnyTrue,
AnyFalse,
}
/// <summary>
/// Тип конвертера, по умолчанию - AllTrue
/// </summary>
public Types Type { get; set; }
public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
switch (Type)
{
case Types.AllTrue:
return values.All(v => (bool)v);
case Types.AllFalse:
return values.All(v => !(bool)v);
case Types.AnyTrue:
return values.Any(v => (bool)v);
case Types.AnyFalse:
return values.Any(v => !(bool)v);
default:
throw new InvalidOperationException();
}
}
public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
{
return new[] { DependencyProperty.UnsetValue };
}
#region MarkupExtension
public BooleanMultiConverter()
{
}
/// <summary>
/// Отображать конвертер в списке
/// </summary>
public override object ProvideValue(IServiceProvider serviceProvider)
{
return this;
}
#endregion
}
}
#region Свойства
public ObservableCollection<MyClass> Collection { get; set; } = new ObservableCollection<MyClass>
{
new MyClass { Name = "Иванов Иван" },
new MyClass { Name = "Петров Пётр" },
new MyClass { Name = "Сидоров Сидор" },
};
public MyClass SelectedCollection { get; set; };
#endregion
#region Команды
private ActionCommand _myCommand;
public ActionCommand MyCommand => _myCommand ?? (_myCommand = new ActionCommand(MyMethod));
private DelegateCommand<MyClass> _myDelegateCommand;
public DelegateCommand<MyClass> MyDelegateCommand => _myDelegateCommand ?? (_myDelegateCommand = new DelegateCommand<MyClass>(MyMethod2, item => item != null);
private void MyMethod()
{
// обработка команды
}
private void MyMethod2(MyClass item)
{
// обработка команды
}
#endregion
<ListBox ItemsSource="{Binding Collection}" SelectedItem="{Binding SelectedItem}"/>
<Button Command="{Binding MyCommand}" Content="Команда 1"/>
<Button Command="{Binding MyDelegateCommand}" CommandParameter="{Binding SelectedItem}" Content="Команда 2"/>
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
<ListBox ItemsSource="{Binding Collection}" SelectedItem="{Binding SelectedItemc}" DisplayMemberPath="Name">
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseDoubleClick">
<i:InvokeCommandAction Command="{Binding MyDelegateCommand}" CommandParameter="{Binding SelectedItem}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</ListBox>
public class DelegateCommand<T> : ICommand
{
#region Private fields
private readonly Action<T> _execute;
private readonly Func<T, bool> _canExecute;
#endregion
#region Constructors
public DelegateCommand(Action<T> execute, Func<T, bool> canExecute = null)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region DelegateCommand
public void Execute(T parameter)
{
var handler = _execute;
if (handler != null)
{
handler(parameter);
}
}
public bool CanExecute(T parameter)
{
var handler = _canExecute;
return handler == null || handler(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
#region ICommand
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute((T)parameter);
}
#endregion
}
public class DelegateCommand : DelegateCommand<object>
{
public DelegateCommand(Action<object> execute, Func<object, bool> canExecute = null)
: base(execute, canExecute)
{
}
}
public class ActionCommand : DelegateCommand<object>, ICommand
{
#region Private fields
private readonly Action _action;
private readonly Func<bool> _canExecute;
#endregion
#region Constructors
public ActionCommand(Action action, Func<bool> canExecute = null)
: base(null, null)
{
_action = action;
_canExecute = canExecute;
}
#endregion
#region ActionCommand
public void Execute()
{
var handler = _action;
if (handler != null)
{
handler();
}
}
public bool CanExecute()
{
var handler = _canExecute;
return handler == null || handler();
}
#endregion
#region ICommand
void ICommand.Execute(object parameter)
{
Execute();
}
bool ICommand.CanExecute(object parameter)
{
return CanExecute();
}
#endregion
}
public class NumericExtensions
{
public static Int32 ToInt32(this Double line)
{
return (Int32)line;
}
public static Int32 ToInt32(this float line)
{
return (Int32)line;
}
public static Int32 ToInt32(this String line)
{
var res;
int.TryParse(line, out res);
return res;
}
// ... для каждого нужного типа
}
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.SqlServer;
using Models;
namespace DatabaseLibrary
{
public class MyConfiguration : DbConfiguration
{
public MyConfiguration()
{
SetExecutionStrategy("System.Data.SqlClient", () => new SqlAzureExecutionStrategy());
SetDefaultConnectionFactory(new LocalDbConnectionFactory("v11.0"));
}
}
[DbConfigurationType(typeof(MyConfiguration))]
public class Database : DbContext
{
private const string ConnectionString = @"мой connection string";
public Database() : base(ConnectionString)
{
}
// мои DbSet-ы
}
}
long Result;
long Sum(List<int> intList)
{
Result = 0;
intList.ForEach(AddElement);
return Result;
}
void AddElement(int i)
{
Result += i;
}
long Sum(List<int> intList)
{
long result = 0;
intList.ForEach(delegate(int i) { result += i; });
return result;
}
long Sum(List<int> intList)
{
long result = 0;
intList.ForEach(i => result += i);
return result;
}
<StackPanel>
<Label Visibility="Collapsed" Content="Неверные данные авторизации" HorizontalAlignment="Center" Margin="10,7,10,0" Width="Auto" Foreground="Red"/>
<Label Content="Логин:"/>
<TextBox x:Name="loginTxt" TextWrapping="NoWrap"/>
<Label Content="Пароль:"/>
<PasswordBox x:Name="passwordTxt"/>
<Button Content="Войти"/>
</StackPanel>
<Window.Resources>
<Style x:Key="CommonStyle" TargetType="Control">
<Setter Property="Margin" Value="5" />
<Setter Property="Padding" Value="5" />
<Setter Property="FontSize" Value="16"/>
<Setter Property="Width" Value="150"/>
</Style>
<Style TargetType="Label" BasedOn="{StaticResource CommonStyle}"/>
<Style TargetType="TextBox" BasedOn="{StaticResource CommonStyle}"/>
<Style TargetType="PasswordBox" BasedOn="{StaticResource CommonStyle}"/>
<Style TargetType="Button" BasedOn="{StaticResource CommonStyle}"/>
</Window.Resources>
class KvadrUr
{
public double A { get; set; }
public double B { get; set; }
public double C { get; set; }
public bool HasRoots { get { return GetDiscr() >= 0; } }
public KvadrUr()
{
}
public KvadrUr(double a, double b, double c)
{
A = a;
B = b;
C = c;
}
public double[] GetRoots()
{
var discr = GetDiscr();
if (discr < 0) return new[] {double.NaN, double.NaN};
var sqrt = Math.Sqrt(discr);
return new[]
{
(-B + sqrt) / (2 * A),
(-B - sqrt) / (2 * A)
};
}
private double GetDiscr()
{
return B*B - 4*A*C;
}
}
interface IRoots
{
bool HasRoots { get; }
double[] GetRoots();
}
class KvadrUr : IRoots
{
// ...
}
System.Int32 i = 10;
System.Console.WriteLine("Строка");
System.Collections.Generic.List<int> list = new System.Collections.Generic.List<int>();
Int32 i = 10;
Console.WriteLine("Строка");
List<int> list = new List<int>();
using IntList = System.Collections.Generic.List<int>;
IntList lst = new IntList();
List<double> lst2 = new List<double>();