我想编写一个代码片段来执行以下操作,就像我有一个类让我们说MyClass:
class MyClass
{
public int Age { get; set; }
public string Name { get; set; }
}
所以代码段应该创建以下方法:
public bool DoUpdate(MyClass myClass)
{
bool isUpdated = false;
if (Age != myClass.Age)
{
isUpdated = true;
Age = myClass.Age;
}
if (Name != myClass.Name)
{
isUpdated = true;
Name = myClass.Name;
}
return isUpdated;
}
所以我的想法是,如果我为任何类调用它应该创建DoUpdate
方法的代码段,并且应该按照我在上面的例子中所做的那样编写所有属性。
所以我想知道:
答案 0 :(得分:1)
您的摘要应在
下C:\ Users \ CooLMinE \ Documents \ Visual Studio(version)\ Code Snippets \ Visual C#\ My Code Snippets
您最简单的方法是获取现有的片段并对其进行修改以避免重建文件的布局。
以下是您可以使用的模板:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<CodeSnippet Format="1.0.0">
<Header>
<Title>snippetTitle</Title>
<Shortcut>snippetShortcutWhichYouWillUseInVS</Shortcut>
<Description>descriptionOfTheSnippet</Description>
<Author>yourname</Author>
<SnippetTypes>
<SnippetType>Expansion</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Declarations>
<Literal>
</Literal>
<Literal Editable="false">
</Literal>
</Declarations>
<Code Language="csharp"><![CDATA[yourcodegoeshere]]>
</Code>
</Snippet>
</CodeSnippet>
</CodeSnippets>
当您希望它根据类名等生成名称时,这应该会派上用场: http://msdn.microsoft.com/en-us/library/ms242312.aspx
答案 1 :(得分:1)
如何改变实用工具方法:
public static class MyUtilities
{
public static bool DoUpdate<T>(
this T target, T source) where T: class
{
if(target == null) throw new ArgumentNullException("target");
if(source == null) throw new ArgumentNullException("source");
if(ReferenceEquals(target, source)) return false;
var props = typeof(T).GetProperties(
BindingFlags.Public | BindingFlags.Instance);
bool result = false;
foreach (var prop in props)
{
if (!prop.CanRead || !prop.CanWrite) continue;
if (prop.GetIndexParameters().Length != 0) continue;
object oldValue = prop.GetValue(target, null),
newValue = prop.GetValue(source, null);
if (!object.Equals(oldValue, newValue))
{
prop.SetValue(target, newValue, null);
result = true;
}
}
return result;
}
}
示例用法:
var a = new MyClass { Name = "abc", Age = 21 };
var b = new MyClass { Name = "abc", Age = 21 };
var c = new MyClass { Name = "def", Age = 21 };
Console.WriteLine(a.DoUpdate(b)); // false - the same
Console.WriteLine(a.DoUpdate(c)); // true - different
Console.WriteLine(a.Name); // "def" - updated
Console.WriteLine(a.Age);
请注意,如果要在紧密循环(等)中使用它,可以进行大量优化,但这样做需要元编程知识。