2020年8月28日 星期五

C# Namespace and Using (轉貼)

 

這樣全階層寫很累耶!!所以可以使用using的方式在檔頭載入,如下

using System;
using MyOwnNameSpace.AppOneFunction;
using MyOwnNameSpace.AppTwoFunction;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            PrintScreen.Print();
            PrintScreen.Print();
        }        
    }
}

但上例是無法使用的,因為我們有說到命名空間可以避免名稱衝突,所以在全部階層都寫的情形下,它允許不同的命名空間可以有相同的成員名稱.

但因為我們使用了using後,把前面的階層拿掉了,你會發現上例的PrintScree.Print()無法明確的判斷到底是那個namespace下的.

解決方法就是使用命名空間的別名,例子如下

using System;
using AppOne = MyOwnNameSpace.AppOneFunction;
using AppTwo = MyOwnNameSpace.AppTwoFunction;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main()
        {
            AppOne.PrintScreen.Print();
            AppTwo.PrintScreen.Print();
        }        
    }
}

這樣程式就能明白你指的是那個PrintScreen.Print()了.

那如果自定義的命名空間不是和你的Main()放在一起的呢??

那你在做自定的命名空間時就要選類別庫的選項來開發,編譯後你會發現在你的專案目錄中有一個相同名稱的DLL檔

你要在你的Main()的專案中,使用加入參考的專案方式,使用檔案瀏覽找到要加入的DLL檔,之後就可以用using的方式加入了.

2020年8月24日 星期一

Alignment and spacing using String.Format (轉貼)

 

Alignment and spacing using String.Format

 
Besides the index, alignment and formatString are two optional arguments of String.Format method. Alignment is followed by index and separated by a comma as you can see in the following syntax. 
  1. String.Format("{index[,alignment][:formatString]}"object);  
By default, strings are right-aligned within their field if you specify a field width. To left-align strings in a field, you preface the field width with a negative sign, such as {0,-12} to define a 12-character right-aligned field.
 
The following code example in Listing 3 creates a formatted table of items with spacing between items that displays a list of published books with their title, price, publisher, and year published. 
  1. Console.WriteLine("***** Alignment ****/");  
  2. string[] books = {"A Programmer's Guide to ADO.NET""Graphics Programming""Programming C#"};  
  3. string[] publishers = {"APress""Addision Wesley""C# Corner" };  
  4. decimal[] prices = { 45.95m, 54.95m, 49.95m };  
  5. int[] years = { 2001, 2002, 2003 };  
  6.   
  7. Console.WriteLine("Mahesh Chand's Books");  
  8. String data = String.Format("{0,-35} {1,-20} {2,-10} {3, -10} \n",  
  9. "Title""Publisher""Price""Year");  
  10. for (int index = 0; index < years.Length; index++)  
  11. data += String.Format("{0,-35} {1,-20} {2, -10} {3, -10} \n",  
  12. books[index], publishers[index], prices[index], years[index]);  
  13. Console.WriteLine($"\n{data}");  

2020年8月19日 星期三

刪除 XML 資料(轉貼)

 

刪除 XML 資料

刪除的動作相當簡單,請見以下範例:

// 刪除篩選到的 XML 元素
xmlDocument.Root?.Elements().Where(x => x.Attribute("Id")?.Value == "106").Remove();

// 刪除根元素底下的所有 XML 元素,以範例來說,為刪除根元素下 Students 元素
xmlDocument.Root?.Elements().Remove();

這裡的 xmlDocument.Root 等價於 xmlDocument.Element("Students"),也就是整份 XML 文件的根結點。若是要表示 XML 文件的起始,建議使用 xmlDocument.Root 來操作會比較符合語意且直覺。

請參考 04-ModifyXmlDocument 專案的 Program.cs


參考資料:


RemoveNodes()

從此文件或項目中移除子節點。

(Inherited from XContainer)

2020年8月17日 星期一

XPath Syntax(轉貼)

 

XPath Syntax


XPath uses path expressions to select nodes or node-sets in an XML document. The node is selected by following a path or steps.


The XML Example Document

We will use the following XML document in the examples below.

<?xml version="1.0" encoding="UTF-8"?>

<bookstore>

<book>
  <title lang="en">Harry Potter</title>
  <price>29.99</price>
</book>

<book>
  <title lang="en">Learning XML</title>
  <price>39.95</price>
</book>

</bookstore>

Selecting Nodes

XPath uses path expressions to select nodes in an XML document. The node is selected by following a path or steps. The most useful path expressions are listed below:

ExpressionDescription
nodenameSelects all nodes with the name "nodename"
/Selects from the root node
//Selects nodes in the document from the current node that match the selection no matter where they are
.Selects the current node
..Selects the parent of the current node
@Selects attributes

In the table below we have listed some path expressions and the result of the expressions:

Path ExpressionResult
bookstoreSelects all nodes with the name "bookstore"
/bookstoreSelects the root element bookstore

Note: If the path starts with a slash ( / ) it always represents an absolute path to an element!

bookstore/bookSelects all book elements that are children of bookstore
//bookSelects all book elements no matter where they are in the document
bookstore//bookSelects all book elements that are descendant of the bookstore element, no matter where they are under the bookstore element
//@langSelects all attributes that are named lang


Predicates

Predicates are used to find a specific node or a node that contains a specific value.

Predicates are always embedded in square brackets.

In the table below we have listed some path expressions with predicates and the result of the expressions:

Path ExpressionResult
/bookstore/book[1]Selects the first book element that is the child of the bookstore element.

Note: In IE 5,6,7,8,9 first node is[0], but according to W3C, it is [1]. To solve this problem in IE, set the SelectionLanguage to XPath:

In JavaScript: xml.setProperty("SelectionLanguage","XPath");
/bookstore/book[last()]Selects the last book element that is the child of the bookstore element
/bookstore/book[last()-1]Selects the last but one book element that is the child of the bookstore element
/bookstore/book[position()<3]Selects the first two book elements that are children of the bookstore element
//title[@lang]Selects all the title elements that have an attribute named lang
//title[@lang='en']Selects all the title elements that have a "lang" attribute with a value of "en"
/bookstore/book[price>35.00]Selects all the book elements of the bookstore element that have a price element with a value greater than 35.00
/bookstore/book[price>35.00]/titleSelects all the title elements of the book elements of the bookstore element that have a price element with a value greater than 35.00

Selecting Unknown Nodes

XPath wildcards can be used to select unknown XML nodes.

WildcardDescription
*Matches any element node
@*Matches any attribute node
node()Matches any node of any kind

In the table below we have listed some path expressions and the result of the expressions:

Path ExpressionResult
/bookstore/*Selects all the child element nodes of the bookstore element
//*Selects all elements in the document
//title[@*]Selects all title elements which have at least one attribute of any kind

Selecting Several Paths

By using the | operator in an XPath expression you can select several paths.

In the table below we have listed some path expressions and the result of the expressions:

Path ExpressionResult
//book/title | //book/priceSelects all the title AND price elements of all book elements
//title | //priceSelects all the title AND price elements in the document
/bookstore/book/title | //priceSelects all the title elements of the book element of the bookstore element AND all the price elements in the document

String Format for Double [C#] (轉貼)

 

String Format for Double [C#]

The following examples show how to format float numbers to string in C#. You can use static method String.Format or instance methods double.ToString and float.ToString.

Digits after decimal point

This example formats double to string with fixed number of decimal places. For two decimal places use pattern „0.00“. If a float number has less decimal places, the rest digits on the right will be zeroes. If it has more decimal places, the number will be rounded.

[C#]
// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

Next example formats double to string with floating number of decimal places. E.g. for maximal two decimal places use pattern „0.##“.

[C#]
// max. two decimal places
String.Format("{0:0.##}", 123.4567);      // "123.46"
String.Format("{0:0.##}", 123.4);         // "123.4"
String.Format("{0:0.##}", 123.0);         // "123"