В C# классы наследуют комментарии из интерфейса.
В JavaDoc всё сложнее - нужно писать над унаследованным свойством:
В JavaDoc всё сложнее - нужно писать над унаследованным свойством:
/**
* {@inheritDoc}
*/
/**
* {@inheritDoc}
*/
trait Animal {
def word: String
def talk() { println(this.word) }
}
class Cat extends Animal { def word = "Meow!" }
class Dog extends Animal { def word = "Woof!" }
class JustACat { def meow = "Meow!" }
class HappyCat extends JustACat with Animal {
def word = meow + " :)"
}
class SadCat extends JustACat with Animal {
def word = meow + " :("
}
val dog = new Dog()
dog.talk
public static TResult With<tinput tresult="">
(this TInput o, Func<tinput tresult=""> evaluator)
where TResult : class
where TInput : class
{
return (o == null) ? return null : evaluator(o);
}
Usage:
string postCode = this.With(x => person) .With(x => x.Address) .With(x => x.PostCode);
public static class FormattableObject
{
public static string ToString(this object anObject, string aFormat)
{
return FormattableObject.ToString(anObject, aFormat, null);
}
public static string ToString(this object anObject, string aFormat, IFormatProvider formatProvider)
{
StringBuilder sb = new StringBuilder();
Type type = anObject.GetType();
Regex reg = new Regex(@"({)([^}]+)(})",RegexOptions.IgnoreCase);
MatchCollection mc = reg.Matches(aFormat);
int startIndex = 0;
foreach(Match m in mc)
{
Group g = m.Groups[2]; //it's second in the match between { and }
int length = g.Index - startIndex -1;
sb.Append(aFormat.Substring(startIndex,length));
string toGet = String.Empty;
string toFormat = String.Empty;
int formatIndex = g.Value.IndexOf(":"); //formatting would be to the right of a :
if (formatIndex == -1) //no formatting, no worries
{
toGet = g.Value;
}
else //pickup the formatting
{
toGet = g.Value.Substring(0,formatIndex);
toFormat = g.Value.Substring(formatIndex+1);
}
//first try properties
PropertyInfo retrievedProperty = type.GetProperty(toGet);
Type retrievedType = null;
object retrievedObject = null;
if(retrievedProperty != null)
{
retrievedType = retrievedProperty.PropertyType;
retrievedObject = retrievedProperty.GetValue(anObject,null);
}
else //try fields
{
FieldInfo retrievedField = type.GetField(toGet);
if (retrievedField != null)
{
retrievedType = retrievedField.FieldType;
retrievedObject = retrievedField.GetValue(anObject);
}
}
if (retrievedType != null ) //Cool, we found something
{
string result = String.Empty;
if(toFormat == String.Empty) //no format info
{
result = retrievedType.InvokeMember("ToString",
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase
,null,retrievedObject,null) as string;
}
else //format info
{
result = retrievedType.InvokeMember("ToString",
BindingFlags.Public | BindingFlags.NonPublic |
BindingFlags.Instance | BindingFlags.InvokeMethod | BindingFlags.IgnoreCase
,null,retrievedObject,new object[]{toFormat,formatProvider}) as string;
}
sb.Append(result);
}
else //didn't find a property with that name, so be gracious and put it back
{
sb.Append("{");
sb.Append(g.Value);
sb.Append("}");
}
startIndex = g.Index + g.Length +1 ;
}
if (startIndex < aFormat.Length) //include the rest (end) of the string
{
sb.Append(aFormat.Substring(startIndex));
}
return sb.ToString();
}
}
Person p = new Person();
string foo = p.ToString("{Money:C} {LastName}, {ScottName} {BirthDate}");
String.Format("{0}://{1}{2}",
Request.ServerVariables["HTTPS"] == "on" ?
"https" :
"http",
Request.ServerVariables["SERVER_NAME"],
Request.RawUrl.ToString());
< telerik:radcomboboxitem runat="server" text="2010" value="10" >
private const int CC_VALID_YEARS_RANGE = 9;
....................................................................................
ddlYear.DataSource = Enumerable.Range(DateTime.Today.Year, CC_VALID_YEARS_RANGE)
.ToDictionary(item => item.ToString(),
item => (item % 1000).ToString());
ddlYear.DataTextField = "Key";
ddlYear.DataValueField = "Value";
ddlYear.DataBind();
А если надо добавить ещё одну строку Year с пустым значением - нужно предварительно сбросить Dictionary в ToList() (получится List < KeyValuePair < string, string > >) и сделать insert в 0-ой индекс. Дело в том, что Dictionary<> сам по себе не сортируется - соответственно, Insert-а в нём нет и foreach перебирает его в том же порядке, в каком элементы добавились.
private const int CC_VALID_YEARS_RANGE = 9;
....................................................................................
List < nKeyValuePair < string, string > > yearsList =
Enumerable.Range(DateTime.Today.Year, CC_VALID_YEARS_RANGE)
.ToDictionary(item => item.ToString(),
item => (item % 1000).ToString()).ToList();
yearsList.Insert(0, new KeyValuePair < string,string > ("Year", String.Empty));
ddlYear.DataSource = yearsList;
ddlYear.DataTextField = "Key";
ddlYear.DataValueField = "Value";
ddlYear.DataBind();
textBox.Attributes.Add("onkeydown", "if(event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('" + buttonDoh.ClientID + "').click();return false;}} else {return true};");
List < sqlcommand > sqlCommands = new List < sqlcommand > ();
foreach (ParsedAddress parsedAddress in parsedAddresses)
{
if (parsedAddress.IsError)
continue;
SqlCommand sqlCommand = new SqlCommand(sqlcmd_SAVE_PARSED_VALUES);
sqlCommand.Parameters.Add(new SqlParameter("Param1", "Param1"));
SqlParameter NullableParameter = new SqlParameter("NullableParameter", SqlDbType.Int);
NullableParameter.IsNullable = true;
if (itemToWrite.NullableValue != null)
NullableParameter.Value = itemToWrite.NullableValue.ID;
else
NullableParameter.Value = DBNull.Value;
sqlCommand.Parameters.Add(NullableParameter);
sqlCommand.Parameters.Add(new SqlParameter("Param2", "Param2"));
sqlCommand.Parameters.Add(new SqlParameter("Param3", 13));
sqlCommands.Add(sqlCommand);
}
SqlConnection connection = new SqlConnection(connectionStringWrite);
connection.Open();
SqlTransaction transaction = connection.BeginTransaction();
try
{
foreach (SqlCommand cmd in sqlCommands)
{
cmd.Connection = connection;
cmd.Transaction = transaction;
cmd.ExecuteNonQuery();
cmd.Dispose();
}
transaction.Commit();
}
catch (SqlException sqlError)
{
transaction.Rollback();
throw sqlError;
}
finally
{
connection.Close();
}
dataGridView.DataSource = null; dataGridView.DataSource = list;
dataGridView.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
string newText = "abc"; // running on worker thread
this.Invoke((MethodInvoker)delegate {
someLabel.Text = newText; // runs on UI thread
});
delegate void UpdateLabelDelegate (string message);
void UpdateLabel (string message)
{
if (InvokeRequired)
{
Invoke (new UpdateLabelDelegate (UpdateLabel), new object[] { message });
return;
}
MyLabelControl.Text = message;
}
private delegate void SetPropertyThreadSafeDelegate(Control @this, Expression< Func > property, TResult value);
public static void SetPropertyThreadSafe(this Control @this, Expression< Func > property, TResult value)
{
var propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
if (propertyInfo == null ||
!@this.GetType().IsSubclassOf(propertyInfo.ReflectedType) ||
@this.GetType().GetProperty(propertyInfo.Name, propertyInfo.PropertyType) == null)
{
throw new ArgumentException("The lambda expression 'property' must reference a valid property on this Control.");
}
if (@this.InvokeRequired)
{
@this.Invoke(new SetPropertyThreadSafeDelegate(SetPropertyThreadSafe), new object[] { @this, property, value });
}
else
{
@this.GetType().InvokeMember(propertyInfo.Name, BindingFlags.SetProperty, null, @this, new object[] { value });
}
}
public static void SetPropertyInGuiThread< C, V >(this C control, Expression< Func < C, V >> property, V value) where C : Control
{
var memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("The 'property' expression must specify a property on the control.");
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
throw new ArgumentException("The 'member' expression must specify a property on the control.");
if (control.InvokeRequired)
control.Invoke(
(Action< C, Expression< Func < C, V >>, V>)SetPropertyInGuiThread,
new object[] { control, property, value }
);
else
propertyInfo.SetValue(control, value, null);
}
comboBox.DataSource = Enum.GetValues(typeof(AnEnumType));
comboBox.SelectedItem = AnEnumType.Value