StringBuilder V.S. String
proven and usable hacks and experience of Internet application development, for my own use.
Posted by
Dillone Hailei Wang 王海磊
at
10/22/2006 02:59:00 PM
Labels: .NET Framework, Class Library, Language
Posted by
Dillone Hailei Wang 王海磊
at
10/20/2006 12:30:00 PM
Labels: .NET Framework, Callback, Language
@ You need to ascertain wheter a method named OneMethod is accessible to a derived class. What shoud you do?
^ Call the IsFamily property of the MethodInfo Class.
@ The IsFamily property gets a value indicating whether the visibility of this method or constructor is described by MethodAttributes.Family; that is, the method or constructor is visible only within its class and derived classes. (Inherited from MethodBase.)
^ Family Indicates that the method is accessible only to members of this class and its derived classes.
^ The MethodAttribute enumeration also contains:
Abstract Indicates that the class does not provide an implementation of this method.
Assembly Indicates that the method is accessible to any class of this assembly.
Final Indicates that the method cannot be overridden.
Private Indicates that the method is accessible only to the current class.
Virtual Indicates that the method is virtual
Static Indicates that the method is defined on the type; otherwise, it is defined per instance.
e You can read more about MethodAttributes's member here.
e About MethodInfo class
Posted by
Dillone Hailei Wang 王海磊
at
10/20/2006 11:04:00 AM
Labels: .NET Framework, Language, Reflection
The Type class有什么用?
@ The Type class represents a single type, allowing you to look at the methods, properties, events, interfaces, and inheritance tree of a particular type in the system.
How to get the Type object?
@ You can get Type object in 4 ways:
@ 1st way: from the Assembly class:
Dim OneAssembly As Assembly = Assembly.GetExecutingAssembly()
Dim AssemblyTypes() As Type = OneAssembly.GetTypes()
@ 2nd way: from the Module class:
Dim AllModulesOfOneAssembly As [Module] = OneAssembly.GetModules()
Dim OneModuleOfOneAssembly As [Module] = AllModulesOfOneAssembly(0)
Dim AllTypesOfOneModuleOfOneAssembly () As Type = OneModuleOfOneAssembly .GetTypes()
@ 3rd way: get the type of the instance of an object by calling its GetType method:
Dim OneObject As New Object()
Dim TypeOfOneObject As Type = OneObject.GetType()
@ 4th way: create a Type object using C# typeof / VB GetType keywork:
Dim OneSpecificType As Type = GetType(Int32) 'VB
Type OneSpecificType = typeof(Int32) //C#
Posted by
Dillone Hailei Wang 王海磊
at
10/19/2006 05:32:00 PM
Labels: .NET Framework, Language, Reflection
^ 有人说有经验的programmer在VB.NET和C#之间转换只需要一个星期的时间,我也觉得不需要费多久。我现在在一个咨询项目里使用这两种语言,经常是今天VB.NET,明天C#,需要做的就是偶尔查查MSDN上的Language Syntax Reference。写程序,关键的是编程思想,语法差别不是重要的。所以,我很乐意地说:VB.NET和C#我都用得挺好。
^ 我从前写了四五年Java,从Java到C#转换我没有感觉有多少困难。反正我写程序的方式、风格、思路还是一样。并且,我还是可以随时用Java编程。所以,我认为:
最重要的是deep understanding of Object-Oriented。
非常重要的是programming patterns and best practices。
很重要的是very familiar with class library。
也很重要的是experienced with top IDEs。
e How popular is VB .NET versus C#?
e VB.NET and C# Comparison
e Java (J2SE 5.0) and C# Comparison
e VB.NET vs C#: The Great .NET Language Debate
Posted by
Dillone Hailei Wang 王海磊
at
10/16/2006 05:56:00 PM
Labels: C#, Java, Language, Object Oriented, VB.NET
@ Properties can be considered smarter fields in that they can be assigned to or read from (like a field), yet when this happens some code in the class executes, and therefore the author of the class can process the value being assigned or returned.
@ Inside the Property block, you write a Get…End Get block, which defines which value the property returns, and a Set…End Set block, which defines how values are assigned to the property.
@ In most cases, a property simply maps to a Private field, so the code for these two blocks often looks like this:Dim m_BirthDate As Date
Public Property BirthDate() As Date
Get
Return m_BirthDate
End Get
Set(ByVal value As Date)
m_BirthDate = value
End Set
End Property
Posted by
Dillone Hailei Wang 王海磊
at
10/16/2006 05:44:00 PM
Labels: .NET Framework, Language, Object Oriented, Property, VB.NET
INSERT INTO TableA (PosID, PosValue, DataDate) SELECT PosID, PosValue, DataDate FROM TableB WHERE DataDate = '2006-10-6' AND PosID = 'TAEE1'
^ 把Values (A,B,C)部分替换成一个SELECT A,B,C语句便可。
UPDATE TableA SET PosValue = (SELECT PosValue FROM TableB WHERE
DataDate = '2006-10-6' AND PosID = 'TAEE1' ) WHERE PosID = 'TAEE1' AND DataDate = '2006-10-6'
^
SELECT OUID, (SELECT ID, OUName FROM Accounts_OU WHERE ID = A.OUID ORDER BY ID) AS OUName FROM BizMgtStationOrder A WHERE PipeLineID = " & XXX & " ORDER BY OUID"
Posted by
Dillone Hailei Wang 王海磊
at
10/13/2006 05:47:00 PM
@ Shared means "shared between all instances of a class", which is also called static.
Posted by
Dillone Hailei Wang 王海磊
at
10/11/2006 01:34:00 PM
Labels: Language
@ The ASP.NET markup language (that is, the ASPX language) is increasingly being recognized as a declarative programming language.
@ Declarative programming is quite a different programming model.
@ When you program with an imperative language, you reach a desired goad by providing the specific operations required to reach the goal. (That is, you tell the computer how to reach your goal.)
@ When you program with a declarative language, you specify your goal and a compiler or interpreter uses its predefined algorithms to determine the appropriate operations to reach that goal. (That is, the computer find a way to reach your goal.)
^ 这就像我曾经说过的,我只在乎是否实现了一个function,而不在乎这个function是怎么被实现的。
e The Right Way to do Ajax is Declaratively
e Declarative V.S. Imperative Programming
e Declarative programming
e del.icio.us/tag/declarative
Posted by
Dillone Hailei Wang 王海磊
at
10/10/2006 06:31:00 PM
Labels: ASP.NET, Language, Programming
@ A procedure is a block of Visual Basic statements enclosed by a declaration statement (Function, Sub, Operator, Get, Set) and a matching End declaration. All executable statements in Visual Basic must be within some procedure.
@ Types of Procedures
Visual Basic uses several types of procedures:
· Sub Procedures perform actions but do not return a value to the calling code.
· Event-handling procedures are Sub procedures that execute in response to an event raised by user action or by an occurrence in a program.
· Function Procedures return a value to the calling code. They can perform other actions before returning.
· Property Procedures return and assign values of properties on objects or modules.
· Operator Procedures define the behavior of a standard operator when one or both of the operands is a newly-defined class or structure.
· Generic Procedures in Visual Basic define one or more type parameters in addition to their normal parameters, so the calling code can pass specific data types each time it makes a call.
Posted by
Dillone Hailei Wang 王海磊
at
10/10/2006 10:15:00 AM
Labels: .NET Framework, Language, Object Oriented, VB.NET
A constructor is a method that runs when a new instance of the class is created.
In Visual Basic, the constructor method is always named Sub New:Class Person
Private CreateTime As Date
Sub New()
' Display a diagnostic message.
Console.WriteLine("A new instance of Person is being created.")
' Remember when this instance was created.
CreateTime = Now
' Perform other initialization chores.
…
End Sub
End Class
Posted by
Dillone Hailei Wang 王海磊
at
10/07/2006 11:42:00 AM
Labels: .NET Framework, Language, Object Oriented, VB.NET
@ Database developers must hava a thorough knowledge of Transact-SQL to read data from and write data to SQL Server database. Using Transact-SQL is the only way to work with the data.
@ Transact-SQL is a fairly simple language; Yet many develpers don't spend the time to understand it, and they end up writing less-than-desirable code.
@ The key to creating well-perfomring Transact-SQL queries is to think in terms of sets instead of row-by-row operations, as you would be in a procedural system.
@ A database developer must ensure that queryies use as few tables as possible to statify the data requirements.
@ Avoid the temptation of creating monolithic, do-everything queries that can be sued to statisfy the requirements of many different parts of the applicaton, or that return data from additional tables just in case it might be necessary in the future.
Posted by
Dillone Hailei Wang 王海磊
at
9/27/2006 05:46:00 PM
^ 对于Generic Dictionary的程序写法:
Dim OneGenericDictionary As New Dictionary(Of Integer, String)
OneGenericDictionary.Add(1, "One")
OneGenericDictionary.Add(2, "Two")
OneGenericDictionary.Add(3, "Three")
For Each OnePare As KeyValuePair(Of Integer, String) In OneGenericDictionary
Console.WriteLine("The pare is {0} : {1}", OnePare.Key.ToString, OnePare.Value.ToString)
Next
Dim OneEnumerator As Dictionary(Of Integer, String).Enumerator = OneGenericDictionary.GetEnumerator()
While OneEnumerator.MoveNext
Console.WriteLine(OneEnumerator.Current.Key & " : " & OneEnumerator.Current.Value)
End While
Posted by
Dillone Hailei Wang 王海磊
at
9/24/2006 12:04:00 PM
Labels: .NET Framework, Class Library, Collection, Generic, Language
ArrayList
@ ArrayList, like most collections, supports several ways to iterate over its contents.
Dim OneArrayList As ArrayList = New ArrayList()
OneArrayList.Add("First")
OneArrayList.Add("Second")
OneArrayList.Add("Three")
OneArrayList.Add("Four")
'Way #1
For Each OneArrayListItem As Object In OneArrayList
Console.WriteLine(OneArrayListItem.ToString)
Next
'Way #2
Dim OneEnumerator As IEnumerator = OneArrayList.GetEnumerator()
While OneEnumerator.MoveNext()
Console.WriteLine(OneEnumerator.Current)
End While
'Way #3
For Indexer As Integer = 0 To OneArrayList.Count - 1
Console.WriteLine(OneArrayList(Indexer))
Next
Dictionary
^ 有两种Standard Dictionary:Hashtable和SortedList,三种Specialized Dictionary:ListDictionary,HybridDictionary和OrderedDictionary。
@ In general, the Hashtable class is a very efficient collection. The only problem with Hashtable is for small collections (fewer than 10 elements) it impede performance. This is where ListDictionary comes in.
@ When you know our collection is small, use a ListDictionary; when your collection is large, use a Hashtable. But what if you just do not know how large your collection is? Use HybridDictionary!
^ 干吗非得整得这么复杂?TNND,让事情简洁明了不行?我就不信性能会差十万八千里。硬件的强大处理能力不知有多少被浪费掉了!何不只用一种Dictionary来满足所有类似需求?HybridDictionary解决了所谓的Hashtable和ListDictionary的efficiency问题。有什么意义?对于efficiency这一点我不太考虑,只当是存在Hashtable一种Dictionary就行了。
@ To accomodate you when you need a fast Dictionary but also need to keep the items in an ordered fashion, the .NET Framework supports the OrderedDictionary.
^ OrderedDictionary除了具备Hashtable的功能之外,还具备了control the order of the elements in the collection的功能。OrderedDirctionry is as if a mix of an ArrayList and a Hashtable. 所以,为了简单起见,作为一种通用解决方案,对于需要Dictionary功能的地方,我就只使用OrderedDictionary,只有有明确需求的时候在研究使用其他的Dictionary.
^ 可是,MD!我发现Hashtable有ContainsKey()和ContainsValue()两个method,可是OrderDictionary没有。虽然OrderDictionry.Contains(Key)可以实现Hashtable.ContainsKey()的功能,却实现不了 Hashtable.ContainsValue()。
^ 也许应该考虑尽量使用Generic Collection吧。还没有研究透。
Posted by
Dillone Hailei Wang 王海磊
at
9/23/2006 12:02:00 PM
Labels: .NET Framework, Class Library, Collection, Language
I. 在VB.NET 2005中,根本就没有四舍五入这个概念。round()不应该被翻译成四舍五入。
II.如何实现四舍五入?
一个同事告诉我一个方法:比如要将一个Double保留到小数点后两位并且四舍五入,那么就把这个Double加上0.005,然后截断到小数点后两位。他说这个方法曾经在很多项目里面用过,没问题。我没仔细测试过,但是想想看,道理上是讲的过去的。
Posted by
Dillone Hailei Wang 王海磊
at
9/20/2006 10:31:00 AM
Labels: Class Library, Hack, Language, VB.NET
虽然写了五年程序了,Java,C#,Ruby on Rails,VB.NET,用过好几种语言,也参加过不少大项目的开发,可总是对自己的编程能力不够有信心。虽然,有的程序也写得很好,却好像从没真正全面地掌握一种语言,没能对所有的特性都了然于心。从开始编程,所有的东西都是自学的,也从来没请过高手指导自己,总感觉不是那么“正”。不像在武术领域有大师言传身教,不像在音乐方面有专业演奏家指导。为啥我靠着吃饭的东东却没有请人指导过呢?吼吼!
现在在准备MCPD的认证考试,第一门又是关于语言的,我选择VB.NET作为考试语言,因为我发现VB.NET的语法和Ruby语言很像,都接近英语,少了很多像C#那样的乱七八糟的符号,更符合我这个“人文大脑”的程序员。嘿嘿。毕竟,我在运用人类语言的方面是有灵性的,可一旦到了数理方面,我就成了某人说的呆瓜了。上次考SCJP,考的Java语言,其实这两门考试的内容差不多,涵盖的都是Object-Oriented Programming的东西,只不过用了两套不同的语言语法而已,思想上没有啥大区别。上次以83%通过的,这次也不会是问题。
复习考试,不求一遍能够完全明白,多看几遍,多做些题,量变成质变。有些语言特性可能自己不理解,但是目前做到知道怎么答题就行了。有用的东西都记录下来,发布在这个Blog上,方便自己以后回来查阅。不懂的地方,就多请教人家,即便是有嘲笑,有脸色,忍了,反正不是我没素养。哈。有机会的话,请一位公司里的编程高手指导一番,咱也提升提升水准。希望在我离开这个行业之前成为一个编程高手,否则总有些逃兵的感觉。
王者之程(程序的程,嘿嘿)
Posted by
Dillone Hailei Wang 王海磊
at
9/19/2006 03:28:00 PM
Labels: Language, Programming, Thinking
@ Fields are variables delcared in the class so that they are available to all code within the class, and are available to each individual object.
@ Fields are also called instance variables or member variables.
@ Fields are used by objects to store data.
@ Typically, fields are Private in scope, available only to the code in the class itself.
Never declare a field as Public, beacuse such a choice directly breaks the concept of encapsulation, since code outside the object can directly change data values without following any rules set in the object.
@ If you want to make the value of a field available to code outside of the object, you should use a property:
Public Class OneClass
Private FieldName As String
Private FieldAge As Integer
Public ReadOnly Property Name() As String
Get
Return FieldName
End Get
End Property
End Class
^ 要实现Java中的Field + Getter & Setter Method的关系,在VB中恐怕就要用Field + Property Method的方法了。
@ You shouldn't confuse fields with properties. In Visual Basic, a Property is a type of method that is geared to retrieving and setting values, while a field is a variable within the class that may hold the value exposed by a Property.
Posted by
Dillone Hailei Wang 王海磊
at
9/19/2006 11:23:00 AM
Labels: .NET Framework, Language
@ A delegate is a class that can hold a reference to a method.
Unlike other classes, a delegate class has a signature, it can hold references only to methods that match its signature.
@ A delegate declaration is sufficient to define a delegate class. the declaration supplies the signature of the delegate, and the CLR provides the implementation.
@ EventHandler is predefined delegate class that specifically represents an event handler method for an event that does not return a value, whose 1st parameter is of type Object and refers to the instance that raises the event, and whose 2nd parameter is derived from type EventArgs and holds the event data.
@ An event is a message sent by an object to signal the occurence of an action.
@ In event communication, the event sender calss does not know which object or method will receive/handle the events it raises. What is needed is an intermediary(or pointer-like mechanism) between the sender and receiver. To associate an event with an event handler, add an instance of the delegate to the event.
@ How to wire up a Event Handler for an Event?
AddHandler OneObject.OneEvent, AddressOf OneEventHandler
Posted by
Dillone Hailei Wang 王海磊
at
9/19/2006 10:02:00 AM
Labels: .NET Framework, Language
不去比较那种技术比另一种好不好。ASP.NET,Ruby on Rails都是非常好的技术,各有各的优势。之所以要掌握ASP.NET是工作的需要;之所以要学会Ruby on Rails是为了改善经济状况。一种技术本身并没有多少意义,只有当这种技术可以被运用了改变一些现状,实现一些梦想的时候,它才存在了价值。
为什么要把自己郁于选择某种技术,选择某个阵营这个问题中呢?无所谓。
为了我想要的生活,为了实现我的梦想,把时间精力比例分配好,尽量找出共通的东西,形成自己的一套方法论,做事!
Posted by
Dillone Hailei Wang 王海磊
at
9/15/2006 03:41:00 PM
Labels: ASP.NET, Language, Ruby, Ruby on Rails
Two Ruby features that are a bit unlike what you may have seen before, and which take some getting used to, are “blocks” and iterators. Instead of looping over an index (like with C, C++, or pre-1.5 Java), or looping over a list (like Perl’s for (@a) {...}, or Python’s for i in aList: ...), with
Ruby you’ll very often instead see
some_list.each do this_item
# We're inside the block.
# deal with this_item.
end
For more info on each
(and it’s friends collect
, find
, inject
, sort
, etc.), see ri Enumerable
(and then ri Enumerable#func_name).
There’s no difference between an expression and a statement. Everything has a value, even if that value is nil. This is possible:
x = 10
y = 11
z = if x < y
true
else
false
end
z # => true
Many Ruby newbies struggle with understanding what Symbols are, and what they can be used for. Symbols can best be described as identities. A symbol is all about who it is, not what it is. Fire upirb
and see the difference:
irb(main):001:0> :george.object_id == :george.object_id
=> true
irb(main):002:0> "george".object_id == "george".object_id
=> false
irb(main):003:0>
The object_id
methods returns the identity of an Object. If two objects have the same object_id
, they are the same (point to thesame Object in memory).
As you can see, once you have used a Symbol once, any Symbol with the same characters references the same Object in memory. For any given two Symbols that represent the same characters, the object_id
s match.
Now take a look at the String (“george”). The object_id
s don’t match. That means they’re referencing two different objects in memory. Whenever you use a new String, Ruby allocates memory for it.
If you’re in doubt whether to use a Symbol or a String, consider what’s more important: the identity of an object (i.e. a Hash key), or the contents (in the example above, “george”).
“Everything is an object” isn’t just hyperbole. Even classes and integers are objects, and you can do the same things with them as with any other object:
# This is the same as
# class MyClass
# attr_accessor :instance_var
# end
MyClass = Class.new do
attr_accessor :instance_var
end
Constants are not really constant. If you modify an already initialized constant, it will trigger a warning, but not halt your program. That isn’t to say you should redefine constants, though.
Ruby enforces some naming conventions. If an identifier starts with a capital letter, it is a constant. If it starts with a dollar sign ($), it is a global variable. If it starts with @
, it is an instance variable. If it
starts with @@
, it is a class variable.
Method names, however, are allowed to start with capital letters. This can
lead to confusion, as the example below shows:
Constant = 10
def Constant
11
end
Now Constant
is 10, but Constant()
is 11.
Ruby doesn’t have keyword parameters, like Python has. However, it can be
faked by using symbols and hashes. Ruby on Rails, among others, uses this
heavily. Example:
def some_keyword_params( params )
params
end
some_keyword_params( :param_one => 10, :param_two => 42 )
# => {:param_one=>10, :param_two=>42}
In Ruby, everything except nil and false is
considered true. In C, Python and many other languages, 0 and possibly other
values, such as empty lists, are consided false. Take a look at the following
Python code (the example applies to other languages, too):
# in Python
if 0:
print "0 is true"
else:
print "0 is false"
This will print “0 is false”. The equivalent Ruby:
# in Ruby
if 0
puts "0 is true"
else
puts "0 is false"
end
Prints “0 is true”.
In the following Ruby code,
class MyClass
private
def a_method; true; end
def another_method; false; end
end
You might expect another_method
to be public. Not so. The
‘private’ access modifier continues until the end of the scope, or until another
access modifier pops up, whichever comes first. By default, methods are
public:
class MyClass
# Now a_method is public
def a_method; true; end
private
# another_method is private
def another_method; false; end
end
public
,private
and protected
are really methods, so they canIn Java, public
means a method is accessible by anyone.protected
means the class’s instances and their ancestors can
access it, but not anyone else, and private
means nobody besides
the classes instances can access the method.
Ruby differs slightly. public
is, naturally, public.private
means the method(s) are accessible only when they can be
called without an explicit receiver. Only self is allowed to be
the receiver of a private method call.
protected
is the one to$ irb
irb(main):001:0> class Test
irb(main):002:1> def func
irb(main):003:2> 99
irb(main):004:2> end
irb(main):005:1>
irb(main):006:1* def ==(other)
irb(main):007:2> func == other.func
irb(main):008:2> end
irb(main):009:1> end
=> nil
irb(main):010:0>
irb(main):011:0* t1 = Test.new
=> #<Test:0xb7db7bbc>
irb(main):012:0> t2 = Test.new
=> #<Test:0xb7daf688>
irb(main):013:0> t1 == t2
=> true
irb(main):014:0> # Now make 'func' private
irb(main):015:0* class Test
irb(main):016:1> private :func
irb(main):017:1> end
=> Test
irb(main):018:0>
irb(main):019:0* t1 == t2
NoMethodError: private method 'func' called for
#<Test:0xb7db7bbc>
from (irb):7:in '=='
from (irb):19
from :0
irb(main):020:0>
Fixnum
Object
, the parent of all objects. Ruby on Rails defines aFixnum
. Watch: class Fixnum
def hours
self * 3600 # number of seconds in an hour
end
alias hour hours
end
# 14 hours from 00:00 January 1st
# (aka when you finally wake up ;)
Time.mktime(2006, 01, 01) + 14.hours # => Sun Jan 01 14:00:00
exit!
etc.) by conventionAll methods that change their arguments don’t end with exclamation marks,
though. Array#replace replaces the contents of an array with the
contents of another array. It doesn’t make much sense to have a method like that
that doesn’t modify self.
Singleton methods are per-object methods. They are only available on the
Object you defined it on.
class Car
def inspect
"Cheap car"
end
end
porsche = Car.new
porsche.inspect # => Cheap car
def porsche.inspect
"Expensive car"
end
porsche.inspect # => Expensive car
# Other objects are not affected
other_car = Car.new
other_car.inspect # => Cheap car
Ruby doesn’t give up if it can’t find a method that responds to a particular
message. It calls the method_missing
method with the name of the
method it couldn’t find and the arguments. By default, method_missing raises a
NameError exception, but you can redefine it to better fit your application, and
many libraries do. Here is an example:
# id is the name of the method called, the * syntax collects
# all the arguments in an array named 'arguments'
def method_missing( id, *arguments )
puts "Method #{id} was called, but not found. It has " +
"these arguments: #{arguments.join(", ")}"
end
__ :a, :b, 10
# => Method __ was called, but not found. It has these
# arguments: a, b, 10
The code above just prints the details of the call, but you are free to
handle the message in any way that is appropriate.
A method call is really a message to another object:
# This
1 + 2
# Is the same as this ...
1.+(2)
# Which is the same as this:
1.send "+", 2
Blocks (closures, really) are heavily used by the standard library. To call a
block, you can either use yield
, or make it a Proc
by
appending a special argument to the argument list, like so:
def block( &the_block )
# Inside here, the_block is the block passed to the method
the_block # return the block
end
adder = block { a, b a + b }
# adder is now a Proc object
adder.class # => Proc
You can create blocks outside of method calls, too, by calling Proc.new with
a block or calling the lambda
method.
Similarly, methods are also Objects in the making:
method(:puts).call "puts is an object!"
# => puts is an object!
Most operators in Ruby are just syntactic sugar (with some precedence rules)
for method calls. You can, for example, override Fixnums + method:
class Fixnum
# You can, but please don't do this
def +( other )
self - other
end
end
You don’t need C++’s operator+
, etc.
[]
and []=
+@
and -@
methods, respectively.The operators below are not syntactic sugar, though. They
are not methods, and cannot be redefined:
=, .., ..., !, not, &&, and, , or, !=, !~, ::
Invar = var +
other_var
, var = var * other_var
, etc. and therefore cannot
Posted by
Dillone Hailei Wang 王海磊
at
9/15/2006 12:03:00 AM